grada-run 0.40.17 → 0.41.1

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
@@ -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.40.17",
3
+ "version": "0.41.1",
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
  });
@@ -480,7 +480,8 @@ resource "aws_subnet" "db_isolated" {
480
480
 
481
481
  // Idempotently appends the isolated-subnet block to network.tf content.
482
482
  // Returns the content unchanged when the block already exists. Uses the
483
- // HCL-aware lookup so a comment quoting the header never false-positives.
483
+ // line-anchored lookup so a `#` comment quoting the header never
484
+ // false-positives.
484
485
  export function ensureIsolatedSubnets(networkTfContent) {
485
486
  const content = String(networkTfContent ?? '');
486
487
  if (findResourceBlock(content, 'aws_subnet', 'db_isolated')) return content;
@@ -1,22 +1,24 @@
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
7
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
8
- import { failCommand, shouldAutoApprove, refuseIfNonInteractive, refuseUnknownFlags } from '../utils/command.js';
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
11
  import { runTerraformCommand, getTerraformOutputs, readLastRunMarker, isInterruptedMarker, ensureTerraformInit, checkOutputsContract, DEFAULT_TERRAFORM_PHASE_TIMEOUT_MS } 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 } from '../utils/terraform-metadata.js';
15
- import { readTerraformComputeTarget } from '../utils/resolvers.js';
14
+ import { requireManagedTree, parseStateBucketBackend, upsertAutoTfvar } from '../utils/terraform-metadata.js';
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, isAuthError, printAwsAuthGuidance } from '../utils/aws.js';
21
+ import { findUnreconciledFiles, isValidAccountId, PLACEHOLDER_ACCOUNT_ID } from '../utils/reconcile.js';
20
22
  import { runWake } from './wake.js';
21
23
 
22
24
  export function parseApplyArgs(argv = []) {
@@ -24,12 +26,153 @@ export function parseApplyArgs(argv = []) {
24
26
  if (args[0] === 'apply' || args[0] === 'deploy') args.shift();
25
27
  const { options, unknown } = parseFlags(args, {
26
28
  boolean: ['force', 'destroy-previous-target', 'force-resume', 'allow-partial-outputs', 'headless', 'auto-approve', 'dry-run'],
27
- string: ['force-unlock'],
29
+ string: ['force-unlock', 'account-id'],
28
30
  });
29
31
  if (unknown.length > 0) options.unknownFlags = unknown;
30
32
  return { force: false, ...options };
31
33
  }
32
34
 
35
+ // Offline reconcile: an `init --offline` tree carries
36
+ // YOUR_AWS_ACCOUNT_ID placeholders instead of an account id and has no
37
+ // state bucket. Resolve the account (explicit flag, else STS ground
38
+ // truth), confirm once, rewrite the files, and ensure the bucket —
39
+ // afterwards the normal flow sees a reconciled tree. Returns
40
+ // { proceed: true } or { proceed: false, result } carrying the
41
+ // refusal/failure for the caller to return.
42
+ export async function reconcileOfflineTree({ targetDir, options = {}, projectName }) {
43
+ const files = findUnreconciledFiles(targetDir);
44
+ let accountId;
45
+ let source;
46
+ const flag = options.accountId;
47
+ if (flag !== undefined && flag !== null) {
48
+ if (!isValidAccountId(flag)) {
49
+ return {
50
+ proceed: false,
51
+ result: await failCommand({
52
+ noExit: isProgrammaticCall(options),
53
+ message: `\n✖ Invalid --account-id "${flag}": ${describeAccountIdShape(flag)}.\n`,
54
+ event: 'infrastructure_applied',
55
+ telemetry: { projectName },
56
+ errorCode: 'INVALID_ACCOUNT_ID',
57
+ reason: 'invalid-account-id',
58
+ }),
59
+ };
60
+ }
61
+ // Ping first: the flag resolves the account, but reconciling and
62
+ // provisioning both need live credentials — fail guided with
63
+ // nothing written rather than stamping files and crashing.
64
+ try {
65
+ await checkAwsCredentials(resolveRegion(options, targetDir));
66
+ } catch {
67
+ return {
68
+ proceed: false,
69
+ result: await failCredentialsMissing(options, projectName, {
70
+ message: '\n✖ Could not verify AWS credentials: configure them first — apply cannot reconcile or provision without them.\n',
71
+ }),
72
+ };
73
+ }
74
+ accountId = flag;
75
+ source = 'flag';
76
+ } else {
77
+ try {
78
+ accountId = (await checkAwsCredentials(resolveRegion(options, targetDir))).accountId;
79
+ source = 'sts';
80
+ } catch {
81
+ return {
82
+ proceed: false,
83
+ result: await failCredentialsMissing(options, projectName, {
84
+ message: '\n✖ Could not resolve the AWS account: configure credentials first — apply cannot provision without them.\n',
85
+ }),
86
+ };
87
+ }
88
+ }
89
+ const from = source === 'flag' ? '--account-id' : 'AWS credentials';
90
+ log.message(`Reconciling ${files.length} offline placeholder file(s) with account ${color.cyan(accountId)} (from ${from}):`);
91
+ for (const file of files) log.message(` ${color.dim('-')} ${file}`);
92
+ const refused = await refuseIfNonInteractive(options, {
93
+ message: '\n✖ apply needs approval to reconcile offline placeholders.',
94
+ hint: ' Re-run with --auto-approve to reconcile non-interactively.\n',
95
+ event: 'infrastructure_applied',
96
+ telemetry: { projectName },
97
+ errorCode: 'RECONCILE_NON_INTERACTIVE',
98
+ });
99
+ if (refused) return { proceed: false, result: refused };
100
+ if (!shouldAutoApprove(options)) {
101
+ const confirmed = await confirm({
102
+ message: 'Rewrite the placeholders and ensure the state bucket?',
103
+ initialValue: false,
104
+ });
105
+ if (confirmed !== true) {
106
+ cancel('Reconcile aborted.');
107
+ process.exit(0);
108
+ }
109
+ }
110
+ for (const file of files) {
111
+ const abs = path.join(targetDir, file);
112
+ fs.writeFileSync(abs, fs.readFileSync(abs, 'utf8').split(PLACEHOLDER_ACCOUNT_ID).join(accountId));
113
+ }
114
+ log.message(color.green(`Rewrote ${files.length} file(s).`));
115
+ const backend = fs.readFileSync(path.join(targetDir, 'terraform', 'backend.tf'), 'utf8');
116
+ const { bucket, region: backendRegion } = parseStateBucketBackend(backend);
117
+ let ensured;
118
+ try {
119
+ ensured = await ensureStateBucketExists({
120
+ region: backendRegion ?? resolveRegion(options, targetDir),
121
+ bucket,
122
+ });
123
+ } catch (error) {
124
+ if (isAuthError(error) || error?.name === 'CredentialsProviderError') {
125
+ return {
126
+ proceed: false,
127
+ result: await failCredentialsMissing(options, projectName, {
128
+ message: '\n✖ AWS credentials expired during reconciliation.\n',
129
+ hint: ' Placeholders are already rewritten; fix credentials and re-run apply to converge.\n',
130
+ }),
131
+ };
132
+ }
133
+ return {
134
+ proceed: false,
135
+ result: await failCommand({
136
+ noExit: isProgrammaticCall(options),
137
+ message: `\n✖ Could not ensure the state bucket "${bucket}": ${error?.message ?? error}.\n`,
138
+ event: 'infrastructure_applied',
139
+ telemetry: { projectName },
140
+ errorCode: 'RECONCILE_BUCKET_FAILED',
141
+ reason: 'reconcile-bucket-failed',
142
+ }),
143
+ };
144
+ }
145
+ trackEvent('apply_reconciled', {
146
+ projectName,
147
+ account_source: source,
148
+ file_count: files.length,
149
+ bucket_created: ensured.created,
150
+ });
151
+ return { proceed: true };
152
+ }
153
+
154
+ function describeAccountIdShape(value) {
155
+ const text = String(value);
156
+ if (!/^\d+$/.test(text)) return 'expected exactly 12 digits, got non-digit characters';
157
+ return `expected exactly 12 digits, got ${text.length}`;
158
+ }
159
+
160
+ // Shared credential-failure exit for every reconcile path: the recovery
161
+ // guidance plus a named code, so the shape can't drift between the
162
+ // resolution ping, the STS fallback, and the bucket ensure.
163
+ async function failCredentialsMissing(options, projectName, { message, hint = null }) {
164
+ printAwsAuthGuidance(options);
165
+ return failCommand({
166
+ noExit: isProgrammaticCall(options),
167
+ message,
168
+ ...(hint === null ? {} : { hint }),
169
+ event: 'infrastructure_applied',
170
+ telemetry: { projectName },
171
+ errorCode: 'AWS_CREDENTIALS_MISSING',
172
+ reason: 'aws-credentials-missing',
173
+ });
174
+ }
175
+
33
176
  // Unlock-and-retry flow for a stale Terraform state lock. Headless
34
177
  // refuses unless `--force-unlock <id>` was passed; interactive asks once.
35
178
  // Retries the apply exactly once, skipping the already-confirmed preview.
@@ -213,14 +356,26 @@ async function applyStackMain(input = {}) {
213
356
  });
214
357
  }
215
358
 
216
- // 1a. Surface an interrupted previous run. Informational only — the
359
+ // 1a. Offline reconcile: an `init --offline` tree still carries
360
+ // account placeholders and has no state bucket — resolve, confirm,
361
+ // rewrite, and ensure it before anything reads the files. Dry runs
362
+ // only warn: previews change nothing.
363
+ const unreconciled = findUnreconciledFiles(targetDir);
364
+ if (unreconciled.length > 0 && !options.isDryRun) {
365
+ const reconciled = await reconcileOfflineTree({ targetDir, options, projectName: path.basename(targetDir) });
366
+ if (!reconciled.proceed) return reconciled.result;
367
+ } else if (unreconciled.length > 0) {
368
+ log.warn(color.yellow('⚠ This tree still carries offline account placeholders. Run a real apply to reconcile it.'));
369
+ }
370
+
371
+ // 1b. Surface an interrupted previous run. Informational only — the
217
372
  // new run overwrites the marker when it starts.
218
373
  const lastRun = readLastRunMarker(targetDir);
219
374
  if (isInterruptedMarker(lastRun)) {
220
375
  log.warn(color.yellow(`⚠ Previous ${lastRun.command || 'terraform'} run was interrupted (started ${lastRun.startedAt || 'unknown'}). If it died mid-apply, review with ${color.green('cd terraform && terraform plan')} before trusting this run.`));
221
376
  }
222
377
 
223
- // 1b. Refuse to apply against an asleep environment: apply resets
378
+ // 1c. Refuse to apply against an asleep environment: apply resets
224
379
  // the app desired count while the database stays stopped, so fresh
225
380
  // tasks would crash-loop. Dry runs change nothing, so they keep the
226
381
  // historical advisory warning instead of the shared gate.
@@ -512,14 +667,44 @@ async function applyStackMain(input = {}) {
512
667
  });
513
668
  }
514
669
 
670
+ if (code === 'OIDC_PROVIDER_CONFLICT' && options._oidcAdopted !== true) {
671
+ // Adopt the shared provider instead of hand-editing: the
672
+ // GitHub provider URL is account-singleton, so the existing
673
+ // provider IS the match — flip the var and retry.
674
+ const refused = await refuseIfNonInteractive(options, {
675
+ message: '\n✖ apply needs approval to adopt the existing GitHub OIDC provider.',
676
+ hint: ' Re-run with --auto-approve to adopt non-interactively.\n',
677
+ event: 'infrastructure_applied',
678
+ telemetry: { projectName: actualProjectName },
679
+ errorCode: 'OIDC_ADOPT_NON_INTERACTIVE',
680
+ });
681
+ if (refused) return refused;
682
+ let adopt = shouldAutoApprove(options);
683
+ if (!adopt) {
684
+ const confirmed = await confirm({
685
+ message: 'Adopt the existing GitHub OIDC provider (writes create_oidc_provider = false) and retry?',
686
+ initialValue: true,
687
+ });
688
+ adopt = !isCancel(confirmed) && confirmed === true;
689
+ }
690
+ 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 });
695
+ }
696
+ // Declined: fall through to the manual guidance below.
697
+ }
698
+
515
699
  if (code === 'OIDC_PROVIDER_CONFLICT') {
700
+ // The override lives in grada.auto.tfvars (machine-owned,
701
+ // survives regeneration) — never in the oidc.tf default.
516
702
  log.error(color.red('GitHub OIDC Provider Conflict Detected'));
517
703
  log.message('AWS only allows one GitHub Actions provider per account, and you already have one configured.');
518
704
  log.message('');
519
705
  log.message(`${color.bold('How to fix this:')}`);
520
- log.message(`1. Open ${color.cyan('terraform/oidc.tf')}`);
521
- log.message(`2. Change ${color.green('create_oidc_provider = true')} to ${color.green('create_oidc_provider = false')}`);
522
- log.message(`3. Run ${color.cyan('npx grada-run apply')} again.`);
706
+ log.message(`1. Adopt the shared provider: ${color.cyan(`echo 'create_oidc_provider = false' >> terraform/grada.auto.tfvars`)}`);
707
+ log.message(`2. Run ${color.cyan('npx grada-run apply')} again.`);
523
708
  } else if (code === 'BACKEND_RECONFIGURE_REQUIRED' || code === 'CLOUDFRONT_IN_PROGRESS' || code === 'DELETION_PROTECTION_ACTIVE') {
524
709
  // Named but flow-neutral: runbook guidance with a coded
525
710
  // 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' },
@@ -155,40 +155,52 @@ async function checkStateLock({ cwd, s3Client, deep }) {
155
155
  const keyMatch = backend.match(/key\s*=\s*"([^"]+)"/);
156
156
  const stateKey = keyMatch ? keyMatch[1] : 'terraform.tfstate';
157
157
  const client = s3Client ?? new S3Client({ region: region ?? 'us-east-2' });
158
- let contents;
158
+ // Workspace states live under `env:/<name>/`, outside the default key
159
+ // prefix — list both so a stuck preview lock surfaces with its
160
+ // workspace instead of reporting a false "no lock".
161
+ const lockKeys = [];
159
162
  try {
160
- const resp = await client.send(new ListObjectsV2Command({ Bucket: bucket, Prefix: stateKey }));
161
- contents = resp.Contents || [];
163
+ for (const prefix of [stateKey, 'env:/']) {
164
+ const resp = await client.send(new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix }));
165
+ for (const entry of resp.Contents || []) {
166
+ if (typeof entry.Key === 'string' && entry.Key.endsWith('.tflock')) lockKeys.push(entry.Key);
167
+ }
168
+ }
162
169
  } catch (error) {
163
170
  if (error?.name === 'NoSuchBucket') return { ok: true, note: 'state bucket absent' };
164
171
  return { ok: true, skipped: 'state bucket unreachable' };
165
172
  }
166
- const lockKey = contents
167
- .map((entry) => entry.Key)
168
- .find((key) => typeof key === 'string' && key.endsWith('.tflock'));
169
- if (!lockKey) return { ok: true };
170
- const detailLines = [`Lock file ${lockKey} is present in the state bucket.`];
171
- if (deep) {
172
- try {
173
- const obj = await client.send(new GetObjectCommand({ Bucket: bucket, Key: lockKey }));
174
- const text = typeof obj.Body?.transformToString === 'function'
175
- ? await obj.Body.transformToString()
176
- : '';
177
- const info = JSON.parse(text);
178
- const who = info.Who ?? info.who ?? 'unknown holder';
179
- const operation = info.Operation ?? info.operation ?? 'unknown operation';
180
- const created = info.Created ?? info.created ?? 'unknown time';
181
- detailLines.push(`Held by ${who} (${operation}, since ${created}).`);
182
- } catch {
183
- // The lock itself is the finding; holder detail is best-effort.
173
+ const uniqueLocks = [...new Set(lockKeys)];
174
+ if (uniqueLocks.length === 0) return { ok: true };
175
+ const detailLines = [];
176
+ for (const lockKey of uniqueLocks) {
177
+ detailLines.push(`Lock file ${lockKey} is present in the state bucket${workspaceSuffix(lockKey)}.`);
178
+ if (deep) {
179
+ try {
180
+ const obj = await client.send(new GetObjectCommand({ Bucket: bucket, Key: lockKey }));
181
+ const text = typeof obj.Body?.transformToString === 'function'
182
+ ? await obj.Body.transformToString()
183
+ : '';
184
+ const info = JSON.parse(text);
185
+ const who = info.Who ?? info.who ?? 'unknown holder';
186
+ const operation = info.Operation ?? info.operation ?? 'unknown operation';
187
+ const created = info.Created ?? info.created ?? 'unknown time';
188
+ detailLines.push(`Held by ${who} (${operation}, since ${created}).`);
189
+ } catch {
190
+ // The lock itself is the finding; holder detail is best-effort.
191
+ }
184
192
  }
185
193
  }
186
194
  return { ok: false, detailLines };
187
195
  }
188
196
 
189
- // Project check: a leftover interrupted/running marker means the last
190
- // Terraform run never settled. Warning-grade (apply proceeds with its own
191
- // warning): surfaces yellow without flipping the verdict red.
197
+ // `env:/pr-12/terraform.tfstate.tflock` → ` (workspace pr-12)`; the
198
+ // default key reports bare, as before.
199
+ function workspaceSuffix(lockKey) {
200
+ const match = /^env:\/([^/]+)\//.exec(lockKey);
201
+ return match ? ` (workspace ${match[1]})` : '';
202
+ }
203
+
192
204
  // Project check: an open `repo:*` OIDC trust lets any GitHub repo's
193
205
  // Actions assume the deploy role. Warning-grade (pre-fix trees render it
194
206
  // by default): surfaces yellow without flipping the verdict red. List
@@ -208,6 +220,9 @@ function checkOidcTrustScope({ cwd }) {
208
220
  };
209
221
  }
210
222
 
223
+ // Project check: a leftover interrupted/running marker means the last
224
+ // Terraform run never settled. Warning-grade (apply proceeds with its own
225
+ // warning): surfaces yellow without flipping the verdict red.
211
226
  function checkInterruptedRun({ cwd }) {
212
227
  const marker = readLastRunMarker(cwd);
213
228
  if (!isInterruptedMarker(marker)) return { ok: true };
@@ -209,6 +209,19 @@ async function runDriftMain(input = {}) {
209
209
  encoding: 'utf8',
210
210
  maxBuffer: 32 * 1024 * 1024,
211
211
  });
212
+ if (planResult?.error?.code === 'ENOBUFS') {
213
+ s.stop(color.red('Terraform plan output too large.'));
214
+ return failCommand({
215
+ noExit,
216
+ message: '\n✖ terraform plan output exceeded the 32MB buffer.\n',
217
+ hint: ' Narrow the plan with -target, or run terraform plan directly for the full output.\n',
218
+ event: 'drift_run',
219
+ telemetry: { projectName, action: 'check' },
220
+ errorCode: 'TERRAFORM_PLAN_TOO_LARGE',
221
+ reason: 'terraform-plan-too-large',
222
+ resultExtra: { region },
223
+ });
224
+ }
212
225
  const status = planResult?.status;
213
226
  if (status === 0) {
214
227
  s.stop(color.green('No drift.'));
@@ -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 } from '@aws-sdk/client-ecs';
7
- import { EC2Client, DescribeAddressesCommand, ReleaseAddressCommand, DescribeVpcsCommand } from '@aws-sdk/client-ec2';
6
+ import { ECSClient, ListClustersCommand, ListServicesCommand, DescribeServicesCommand } from '@aws-sdk/client-ecs';
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,51 @@ 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 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.
146
+ export async function listProjectClusterServices({ ecsClient = null, projectName, resourceSuffix = '' } = {}) {
147
+ const byCluster = new Map();
148
+ try {
149
+ if (!ecsClient) return { byCluster, unknown: false };
150
+ const clusterPattern = new RegExp(`^${escapeRegExp(projectName)}(-pr-\\d+)?${escapeRegExp(resourceSuffix)}-cluster$`);
151
+ let nextToken;
152
+ const clusters = [];
153
+ do {
154
+ const resp = await ecsClient.send(new ListClustersCommand({ nextToken, maxResults: 100 }));
155
+ for (const arn of resp.clusterArns || []) {
156
+ const name = String(arn).split('/').pop();
157
+ if (clusterPattern.test(name)) clusters.push(name);
158
+ }
159
+ nextToken = resp.nextToken;
160
+ } while (nextToken);
161
+ for (const cluster of clusters) {
162
+ let svcToken;
163
+ const arns = [];
164
+ do {
165
+ const resp = await ecsClient.send(new ListServicesCommand({ cluster, nextToken: svcToken, maxResults: 100 }));
166
+ arns.push(...(resp.serviceArns || []));
167
+ svcToken = resp.nextToken;
168
+ } while (svcToken);
169
+ byCluster.set(cluster, arns);
170
+ }
171
+ } catch {
172
+ return { byCluster, unknown: true };
173
+ }
174
+ return { byCluster, unknown: false };
175
+ }
176
+
141
177
  export async function discoverLivePreviewLogGroups({
142
178
  ecsClient = null,
143
- cluster = null,
144
179
  projectName,
145
180
  resourceSuffix = '',
146
181
  isLambda = false,
147
182
  listFunctionsImpl = defaultListLambdaFunctionNames,
148
183
  spawnSyncImpl = null,
149
184
  region = null,
185
+ clusterServices = null,
150
186
  } = {}) {
151
187
  const live = new Set();
152
188
  try {
@@ -158,17 +194,15 @@ export async function discoverLivePreviewLogGroups({
158
194
  if (typeof name === 'string' && fnPattern.test(name)) live.add(`/aws/lambda/${name}`);
159
195
  }
160
196
  } else {
161
- if (!ecsClient || !cluster) return { groups: live, unknown: false };
197
+ const enumeration = clusterServices ?? await listProjectClusterServices({ ecsClient, projectName, resourceSuffix });
198
+ if (enumeration.unknown) return { groups: live, unknown: true };
162
199
  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 || []) {
200
+ for (const arns of enumeration.byCluster.values()) {
201
+ for (const arn of arns || []) {
167
202
  const name = String(arn).split('/').pop();
168
203
  if (servicePattern.test(name)) live.add(`/ecs/${name.slice(0, -'-service'.length)}`);
169
204
  }
170
- nextToken = resp.nextToken;
171
- } while (nextToken);
205
+ }
172
206
  }
173
207
  } catch {
174
208
  return { groups: live, unknown: true };
@@ -227,29 +261,78 @@ async function discoverUnattachedEips({ ec2Client, projectName }) {
227
261
  }
228
262
 
229
263
  // 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.
233
- async function discoverDeepVpcs({ ec2Client, projectName }) {
264
+ // predicate — exact project tag only, minus live networks. Foreign and
265
+ // untagged VPCs land in reportOnly, never in deletable, so prefix
266
+ // lookalikes (`myapp-evil`) and legacy resources can never enter the
267
+ // deletion set.
268
+ // Live VPC ids behind running (or desired) ECS services: services →
269
+ // awsvpc subnets → VPCs, across every project cluster (each preview
270
+ // workspace runs its own cluster in its own VPC). Fail-closed like the
271
+ // preview-log-group liveness: any client error resolves `unknown`
272
+ // instead of guessing.
273
+ export async function discoverLiveVpcIds({ ecsClient = null, ec2Client = null, projectName, resourceSuffix = '', clusterServices = null } = {}) {
274
+ const vpcIds = new Set();
275
+ try {
276
+ if (!ecsClient || !ec2Client) return { vpcIds, unknown: false };
277
+ const enumeration = clusterServices ?? await listProjectClusterServices({ ecsClient, projectName, resourceSuffix });
278
+ if (enumeration.unknown) return { vpcIds, unknown: true };
279
+ const subnetIds = new Set();
280
+ for (const [cluster, arns] of enumeration.byCluster.entries()) {
281
+ for (const batch of chunkArray(arns, 10)) {
282
+ const desc = await ecsClient.send(new DescribeServicesCommand({ cluster, services: batch }));
283
+ for (const svc of desc.services || []) {
284
+ // Desired counts: a crash-looping preview runs nothing
285
+ // yet is unambiguously live.
286
+ if ((svc.desiredCount ?? 0) <= 0 && (svc.runningCount ?? 0) <= 0) continue;
287
+ for (const id of svc.networkConfiguration?.awsvpcConfiguration?.subnets || []) subnetIds.add(id);
288
+ }
289
+ }
290
+ }
291
+ if (subnetIds.size > 0) {
292
+ const subs = await ec2Client.send(new DescribeSubnetsCommand({ SubnetIds: [...subnetIds] }));
293
+ for (const sn of subs.Subnets || []) if (sn.VpcId) vpcIds.add(sn.VpcId);
294
+ }
295
+ } catch {
296
+ return { vpcIds, unknown: true };
297
+ }
298
+ return { vpcIds, unknown: false };
299
+ }
300
+
301
+ async function discoverDeepVpcs({ ec2Client, ecsClient = null, projectName, resourceSuffix = '', isLambda = false, clusterServices = null }) {
234
302
  const deletable = [];
235
303
  const reportOnly = [];
304
+ // The stack's own default-workspace VPC is live by construction —
305
+ // asleep stacks run nothing, so task liveness alone would propose
306
+ // deleting the slept network. (Lambda trees create no VPCs, so the
307
+ // Name check is the whole liveness story there.)
308
+ const defaultVpcName = `${projectName}${resourceSuffix}-vpc`;
309
+ const live = isLambda
310
+ ? { vpcIds: new Set(), unknown: false }
311
+ : await discoverLiveVpcIds({ ecsClient, ec2Client, projectName, resourceSuffix, clusterServices });
236
312
  let nextToken;
237
313
  do {
238
314
  const resp = await ec2Client.send(new DescribeVpcsCommand({ NextToken: nextToken }));
239
315
  for (const vpc of resp.Vpcs || []) {
240
316
  const entry = { kind: 'vpc', id: vpc.VpcId };
241
- if (hasExactProjectTag(vpc.Tags, projectName)) {
242
- deletable.push(entry);
243
- } else {
317
+ if (!hasExactProjectTag(vpc.Tags, projectName)) {
244
318
  reportOnly.push({
245
319
  ...entry,
246
320
  reason: Array.isArray(vpc.Tags) && vpc.Tags.length > 0 ? 'foreign-project' : 'unscoped',
247
321
  });
322
+ continue;
323
+ }
324
+ const name = (vpc.Tags || []).find((tag) => tag?.Key === 'Name')?.Value;
325
+ if (name === defaultVpcName || live.vpcIds.has(vpc.VpcId)) {
326
+ reportOnly.push({ ...entry, reason: 'live-excluded' });
327
+ } else if (live.unknown) {
328
+ reportOnly.push({ ...entry, reason: 'liveness-unknown' });
329
+ } else {
330
+ deletable.push(entry);
248
331
  }
249
332
  }
250
333
  nextToken = resp.NextToken;
251
334
  } while (nextToken);
252
- return { deletable, reportOnly };
335
+ return { deletable, reportOnly, unknown: live.unknown };
253
336
  }
254
337
 
255
338
  // Deep target discovery: secrets are report-only, never deletable —
@@ -348,12 +431,14 @@ export async function discoverOrphanedResources(ctx) {
348
431
  export async function discoverDeepOrphans(ctx) {
349
432
  const deletable = [];
350
433
  const reportOnly = [];
434
+ let unknown = false;
351
435
  for (const target of GC_TARGETS.filter((entry) => entry.scope === 'deep')) {
352
436
  const found = await target.discover(ctx);
353
437
  deletable.push(...(found.deletable || []));
354
438
  reportOnly.push(...(found.reportOnly || []));
439
+ if (found.unknown === true) unknown = true;
355
440
  }
356
- return { deletable, reportOnly };
441
+ return { deletable, reportOnly, unknown };
357
442
  }
358
443
 
359
444
  export const ECR_BATCH_DELETE_LIMIT = 100;
@@ -441,7 +526,11 @@ function printDeepReport(deep, projectName) {
441
526
  ? 'owned — secrets are never auto-deleted'
442
527
  : entry.reason === 'prefix-report-only'
443
528
  ? 'name-prefix match — review before acting'
444
- : 'never deleted by gc';
529
+ : entry.reason === 'live-excluded'
530
+ ? 'live — excluded'
531
+ : entry.reason === 'liveness-unknown'
532
+ ? 'liveness unverifiable — review before acting'
533
+ : 'never deleted by gc';
445
534
  console.log(` ${color.dim('-')} ${entry.kind}/${entry.id} ${color.dim(`(${why})`)}`);
446
535
  }
447
536
  console.log('');
@@ -487,17 +576,23 @@ async function runGcMain(input = {}) {
487
576
 
488
577
  let discovered;
489
578
  let previewLivenessUnknown = false;
579
+ let previewClusterServices = null;
490
580
  try {
491
581
  const isLambda = isComputeTarget(cwd, 'lambda');
492
582
  const suffix = readResourceSuffix(cwd);
583
+ // One cluster-service enumeration shared by the log-group and
584
+ // (deep) VPC liveness consumers — fetched once, not per scan.
585
+ previewClusterServices = isLambda
586
+ ? null
587
+ : await listProjectClusterServices({ ecsClient, projectName, resourceSuffix: suffix });
493
588
  const liveness = await discoverLivePreviewLogGroups({
494
589
  ecsClient,
495
- cluster: resolveCluster(options, cwd),
496
590
  projectName,
497
591
  resourceSuffix: suffix,
498
592
  isLambda,
499
593
  spawnSyncImpl: options.spawnSyncImpl,
500
594
  region,
595
+ clusterServices: previewClusterServices,
501
596
  });
502
597
  previewLivenessUnknown = liveness.unknown;
503
598
  discovered = await discoverOrphanedResources({
@@ -536,16 +631,24 @@ async function runGcMain(input = {}) {
536
631
  console.log(color.dim(`Total orphaned resources: ${discovered.totalCount}`));
537
632
 
538
633
  // Deep scan (opt-in): report-only audit of tag-keyed orphans (VPCs,
539
- // secrets, state bucket). Never prompts, never deletes — the
540
- // deletable partition only admits exact project tags, but even those
541
- // need orphan verification (a live project's VPC matches too) before
542
- // any future deletion acts on them.
634
+ // secrets, state bucket). Never prompts, never deletes — VPC
635
+ // candidates additionally pass ECS liveness plus the stack-VPC name
636
+ // check, so live networks land in report-only, never deletable.
543
637
  if (deep) {
544
638
  const ds = spinner();
545
639
  ds.start('Deep scanning tag-keyed orphans...');
546
640
  let deepResult;
547
641
  try {
548
- deepResult = await discoverDeepOrphans({ ec2Client, secretsClient, cwd, projectName });
642
+ deepResult = await discoverDeepOrphans({
643
+ ec2Client,
644
+ secretsClient,
645
+ cwd,
646
+ projectName,
647
+ ecsClient,
648
+ resourceSuffix: readResourceSuffix(cwd),
649
+ isLambda: isComputeTarget(cwd, 'lambda'),
650
+ clusterServices: previewClusterServices,
651
+ });
549
652
  } catch (error) {
550
653
  ds.stop(color.red('❌ Deep discovery failed.'));
551
654
  await trackFailure('gc_run', { projectName, deep: true, error_message: error?.message });
@@ -557,10 +660,14 @@ async function runGcMain(input = {}) {
557
660
  });
558
661
  }
559
662
  ds.stop('Deep discovery complete.');
663
+ if (deepResult.unknown === true) {
664
+ console.log(color.yellow('⚠ VPC liveness could not be verified — no VPCs will be proposed. Check credentials (ECS/EC2) and retry.'));
665
+ }
560
666
  printDeepReport(deepResult, projectName);
561
667
  const deepCounts = {
562
668
  vpc_deletable: deepResult.deletable.filter((entry) => entry.kind === 'vpc').length,
563
669
  vpc_report_only: deepResult.reportOnly.filter((entry) => entry.kind === 'vpc').length,
670
+ vpc_liveness_unknown: deepResult.unknown === true,
564
671
  secret_report_only: deepResult.reportOnly.filter((entry) => entry.kind === 'secret').length,
565
672
  state_bucket_report_only: deepResult.reportOnly.filter((entry) => entry.kind === 'state-bucket').length,
566
673
  };
@@ -41,11 +41,13 @@ import { getBaseRules, getCursorRules, injectManagedBlock } from '../utils/ai-ru
41
41
  import { readFileSafe, COMPUTE_TARGETS, resolveHeadless, resolveInitSuffix, readTerraformProjectName, readTerraformOidcTrust } from '../utils/resolvers.js';
42
42
  import { readGitHubRepoFromRemote, isValidGitHubRepoSlug } from '../utils/git.js';
43
43
  import { parseDomainTf } from '../utils/domains.js';
44
+ import { PLACEHOLDER_ACCOUNT_ID } from '../utils/reconcile.js';
44
45
 
45
46
  // Greppable, invalid-as-real placeholder stamped into backend.tf and
46
47
  // workflow role ARNs by `init --offline`. Uppercase by design: S3 rejects
47
- // it, so an unreconciled tree fails loud at `terraform init`.
48
- export const OFFLINE_ACCOUNT_PLACEHOLDER = 'YOUR_AWS_ACCOUNT_ID';
48
+ // it, so an unreconciled tree fails loud at `terraform init`. Single
49
+ // source lives in reconcile.js; this alias keeps the init-facing name.
50
+ export const OFFLINE_ACCOUNT_PLACEHOLDER = PLACEHOLDER_ACCOUNT_ID;
49
51
 
50
52
  // Reconciliation checklist for offline scaffolds. console.log (not clack)
51
53
  // so it lands in CI logs as well as terminals. Mirrors every call
@@ -1,12 +1,19 @@
1
1
  import { normalizeArgv } from '../utils/args.js';
2
2
 
3
+ // The only meaningful --no-telemetry spellings (bare, =true, =false —
4
+ // the getBoolFlag convention). Anything else (=garbage, or a flag-like
5
+ // *value* such as --cmd "--no-telemetry=x") is not a global: it flows
6
+ // through to per-command parsing, where the unknown-flag gate rejects
7
+ // it loudly instead of this layer silently eating a command value.
8
+ const GLOBAL_ONLY_FLAGS = new Set(['--no-telemetry', '--no-telemetry=true', '--no-telemetry=false']);
9
+
3
10
  export function parseCliArgs(processArgs) {
4
11
  const argv = normalizeArgv(processArgs);
5
12
  // 1. Extract telemetry flag safely
6
- const hasNoTelemetry = argv.some(arg => arg === '--no-telemetry' || (typeof arg === 'string' && arg.startsWith('--no-telemetry=')));
13
+ const hasNoTelemetry = argv.some(arg => arg === '--no-telemetry' || arg === '--no-telemetry=true');
7
14
 
8
15
  // 2. Filter out telemetry flag
9
- const args = argv.filter(arg => arg !== '--no-telemetry' && !(typeof arg === 'string' && arg.startsWith('--no-telemetry=')));
16
+ const args = argv.filter(arg => !GLOBAL_ONLY_FLAGS.has(arg));
10
17
 
11
18
  // 3. Flag readers. Every value flag supports both `--flag=value` and
12
19
  // `--flag value` spellings; space-form values are recorded in
@@ -159,9 +166,9 @@ export function parseCliArgs(processArgs) {
159
166
  // Args for per-command parsers: --no-telemetry is honored globally via
160
167
  // DO_NOT_TRACK (see parseCliArgs), so it must not reach parseFlags —
161
168
  // otherwise the unknown-flag gate would reject a documented global
162
- // option on every command. Every other token passes through untouched.
169
+ // option on every command. Only meaningful spellings are stripped; a
170
+ // flag-like value (e.g. --cmd "--no-telemetry=x") passes through to the
171
+ // command untouched.
163
172
  export function stripGlobalOnlyFlags(processArgs) {
164
- return normalizeArgv(processArgs).filter(
165
- (arg) => arg !== '--no-telemetry' && !(typeof arg === 'string' && arg.startsWith('--no-telemetry='))
166
- );
173
+ return normalizeArgv(processArgs).filter((arg) => !GLOBAL_ONLY_FLAGS.has(arg));
167
174
  }
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)) {
package/src/utils/aws.js CHANGED
@@ -132,9 +132,10 @@ export async function provisionStateBucket(region, projectName) {
132
132
  // 2. Format Bucket Name
133
133
  const stateBucketName = formatStateBucketName(projectName, awsAccountId);
134
134
 
135
- // 3. Create S3 Bucket & Enable Versioning
135
+ // 3. Create S3 Bucket & Enable Versioning (shared helper, so init,
136
+ // recovery, and apply reconcile create identical buckets).
136
137
  const s3Client = new S3Client({ region });
137
- await createVersionedBucket(s3Client, stateBucketName, region);
138
+ await ensureStateBucketExists({ region, bucket: stateBucketName, s3Client });
138
139
 
139
140
  return { awsAccountId, stateBucketName, s3Client };
140
141
  }
@@ -142,14 +143,16 @@ export async function provisionStateBucket(region, projectName) {
142
143
  // Creates (or re-creates) one explicitly named state bucket with the same
143
144
  // tagging + versioning provisionStateBucket applies. Recovery reads the
144
145
  // bucket from backend.tf and lands here instead of re-deriving the name,
145
- // which would miss on suffixed trees.
146
- export async function ensureStateBucketExists({ region, bucket }) {
146
+ // which would miss on suffixed trees. `created` reports whether this
147
+ // call made the bucket (vs finding it already owned) so callers can
148
+ // tell creation from adoption without an extra HeadBucket round trip.
149
+ export async function ensureStateBucketExists({ region, bucket, s3Client = null }) {
147
150
  if (process.env.CI_MOCK_AWS === 'true') {
148
- return { bucket, mocked: true };
151
+ return { bucket, mocked: true, created: false };
149
152
  }
150
- const s3Client = new S3Client({ region });
151
- await createVersionedBucket(s3Client, bucket, region);
152
- return { bucket };
153
+ const client = s3Client ?? new S3Client({ region });
154
+ const { created } = await createVersionedBucket(client, bucket, region);
155
+ return { bucket, created };
153
156
  }
154
157
 
155
158
  async function createVersionedBucket(s3Client, bucket, region) {
@@ -158,26 +161,28 @@ async function createVersionedBucket(s3Client, bucket, region) {
158
161
  Bucket: bucket,
159
162
  CreateBucketConfiguration: region === 'us-east-1' ? undefined : { LocationConstraint: region }
160
163
  }));
161
-
162
- await s3Client.send(new PutBucketTaggingCommand({
163
- Bucket: bucket,
164
- Tagging: {
165
- TagSet: [
166
- { Key: "ManagedBy", Value: "grada" }
167
- ]
168
- }
169
- }));
170
-
171
- await s3Client.send(new PutBucketVersioningCommand({
172
- Bucket: bucket,
173
- VersioningConfiguration: { Status: 'Enabled' }
174
- }));
175
164
  } catch (error) {
176
165
  // Ignore if the bucket already exists and is owned by the user
177
166
  if (error.name !== 'BucketAlreadyOwnedByYou') {
178
167
  throw error;
179
168
  }
169
+ return { created: false };
180
170
  }
171
+
172
+ await s3Client.send(new PutBucketTaggingCommand({
173
+ Bucket: bucket,
174
+ Tagging: {
175
+ TagSet: [
176
+ { Key: "ManagedBy", Value: "grada" }
177
+ ]
178
+ }
179
+ }));
180
+
181
+ await s3Client.send(new PutBucketVersioningCommand({
182
+ Bucket: bucket,
183
+ VersioningConfiguration: { Status: 'Enabled' }
184
+ }));
185
+ return { created: true };
181
186
  }
182
187
 
183
188
  export async function teardownStateBucket(region, bucketName, options = {}) {
@@ -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',
@@ -127,25 +127,3 @@ export async function withProjectLock(cwd, fn, options = {}) {
127
127
  releaseLock(lockDir);
128
128
  }
129
129
  }
130
-
131
- // Synchronous single-attempt variant for sync-only call sites (domain
132
- // provider injection). Never waits: takes over stale locks, otherwise
133
- // throws FILE_LOCK_TIMEOUT immediately.
134
- export function withProjectLockSync(cwd, fn, options = {}) {
135
- const { scope = 'project', staleMs = DEFAULT_LOCK_STALE_MS } = options || {};
136
- const lockDir = lockDirFor(cwd, scope);
137
- fs.mkdirSync(path.dirname(lockDir), { recursive: true });
138
- if (!tryAcquire(lockDir)) {
139
- if (lockAgeMs(lockDir) > staleMs) {
140
- releaseLock(lockDir);
141
- if (!tryAcquire(lockDir)) throw timeoutError(scope, 0);
142
- } else {
143
- throw timeoutError(scope, 0);
144
- }
145
- }
146
- try {
147
- return fn();
148
- } finally {
149
- releaseLock(lockDir);
150
- }
151
- }
package/src/utils/hcl.js CHANGED
@@ -92,11 +92,14 @@ function escapeRegExp(raw) {
92
92
 
93
93
  // Locates `resource "<type>" "<name>" { ... }`. Returns
94
94
  // `{ headerIdx, openIdx, closeIdx }` or null when the resource or its
95
- // braces cannot be found.
95
+ // braces cannot be found. The header anchors to a line start (resource
96
+ // blocks are top-level), so a `#` comment quoting the header never
97
+ // false-positives.
96
98
  export function findResourceBlock(content, resourceType, resourceName) {
97
99
  const text = String(content ?? '');
98
100
  const pattern = new RegExp(
99
- `resource\\s+"${escapeRegExp(resourceType)}"\\s+"${escapeRegExp(resourceName)}"`
101
+ `^[ \t]*resource\\s+"${escapeRegExp(resourceType)}"\\s+"${escapeRegExp(resourceName)}"`,
102
+ 'm'
100
103
  );
101
104
  const match = pattern.exec(text);
102
105
  if (!match) return null;
@@ -0,0 +1,40 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ // Token offline scaffolds (`init --offline`) leave where the AWS account
5
+ // ID belongs: the bucket name in terraform/backend.tf plus every
6
+ // role-to-assume ARN in .github/workflows/*.yml. Detection only —
7
+ // rewriting lives in apply's reconcile pre-step.
8
+ export const PLACEHOLDER_ACCOUNT_ID = 'YOUR_AWS_ACCOUNT_ID';
9
+
10
+ // Repo-relative paths still containing the placeholder (`[]` when the
11
+ // tree is reconciled). Missing files are skipped, never an error; the
12
+ // workflows directory is globbed (not filename-hardcoded) so future
13
+ // workflows are covered.
14
+ export function findUnreconciledFiles(targetDir) {
15
+ const found = [];
16
+ const check = (repoPath) => {
17
+ let content;
18
+ try {
19
+ content = fs.readFileSync(path.join(targetDir, repoPath), 'utf8');
20
+ } catch {
21
+ return;
22
+ }
23
+ if (content.includes(PLACEHOLDER_ACCOUNT_ID)) found.push(repoPath);
24
+ };
25
+ check(path.join('terraform', 'backend.tf'));
26
+ let entries = [];
27
+ try {
28
+ entries = fs.readdirSync(path.join(targetDir, '.github', 'workflows'));
29
+ } catch {
30
+ entries = [];
31
+ }
32
+ for (const entry of entries.filter((name) => /\.ya?ml$/.test(name)).sort()) {
33
+ check(path.join('.github', 'workflows', entry));
34
+ }
35
+ return found.sort();
36
+ }
37
+
38
+ export function isValidAccountId(value) {
39
+ return typeof value === 'string' && /^\d{12}$/.test(value);
40
+ }
@@ -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(`^${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
@@ -53,10 +53,6 @@ export function isInterruptedMarker(marker) {
53
53
  // output would otherwise replace them.
54
54
  const SUMMARY_LINE_RE = /^(Plan:|Apply complete!|Destroy complete!|No changes\.)/;
55
55
 
56
- function notify(spin, text) {
57
- if (spin && typeof spin.message === 'function') spin.message(text);
58
- }
59
-
60
56
  // Runs a terraform command while piping the latest stdout line into a
61
57
  // @clack spinner. Resolves on exit 0; rejects with a structured error
62
58
  // (`{ code, stderr, lockId? }` classified via terraform-errors.js)
@@ -68,8 +64,27 @@ function notify(spin, text) {
68
64
  // last-run marker records running/completed/failed/interrupted for the
69
65
  // next command to report. `onStdoutLine` observes raw lines (used by
70
66
  // getTerraformOutputs); listeners and timers are always released.
67
+ //
68
+ // Progress display: a live terminal rewrites one spinner line, but the
69
+ // spinner re-renders every ~80ms — wherever cursor movement isn't
70
+ // honored (piped output, log viewers) each tick becomes a line and
71
+ // quiet stretches repeat the same message dozens of times. Non-TTY
72
+ // runs therefore get deduped plain lines instead, and the caller's
73
+ // 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.
71
76
  export function runTerraformCommand(args, cwd, spin, loadingPrefix, options = {}) {
72
- const { markerDir = null, timeoutMs = 0, onStdoutLine = null } = options || {};
77
+ const { markerDir = null, timeoutMs = 0, onStdoutLine = null, isTTY = process.stdout?.isTTY } = options || {};
78
+ const wantsProgress = spin && typeof spin.message === 'function';
79
+ const live = isTTY === true && wantsProgress;
80
+ let lastEmitted;
81
+ const emit = (text) => {
82
+ if (lastEmitted === text) return;
83
+ lastEmitted = text;
84
+ if (live) spin.message(text);
85
+ else if (wantsProgress) console.log(text);
86
+ };
87
+ if (wantsProgress && !live && typeof spin.clear === 'function') spin.clear();
73
88
  return new Promise((resolve, reject) => {
74
89
  const child = spawn('terraform', args, { cwd });
75
90
  let errorOutput = '';
@@ -191,13 +206,13 @@ export function runTerraformCommand(args, cwd, spin, loadingPrefix, options = {}
191
206
  for (const line of lines) {
192
207
  const trimmed = line.trim();
193
208
  if (SUMMARY_LINE_RE.test(trimmed)) {
194
- notify(spin, `${loadingPrefix} - ${color.dim(trimmed)}`);
209
+ emit(`${loadingPrefix} - ${color.dim(trimmed)}`);
195
210
  }
196
211
  }
197
212
  if (lines.length > 0) {
198
213
  const latestLine = lines[lines.length - 1].trim();
199
214
  const display = latestLine.length > 120 ? latestLine.substring(0, 117) + '...' : latestLine;
200
- notify(spin, `${loadingPrefix} - ${color.dim(display)}`);
215
+ emit(`${loadingPrefix} - ${color.dim(display)}`);
201
216
  }
202
217
  });
203
218
 
@@ -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