grada-run 0.49.8 → 0.49.10

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.
@@ -76,6 +76,9 @@ export function printOfflineChecklist({ bucket, region, workflows = ['deploy', '
76
76
  // didn't resolve under global installs.
77
77
  const CLI_VERSION = getCliVersion();
78
78
 
79
+ // Database engines init accepts (flag validation + config defaulting).
80
+ const VALID_DB_ENGINES = ['postgres', 'mysql', 'aurora-postgresql'];
81
+
79
82
  // Programmatic entry wrapper: stamps cli_command for telemetry on every
80
83
  // invocation path, including direct imports that bypass bin/cli.js and MCP.
81
84
  export async function mainStack(input = {}) {
@@ -302,422 +305,571 @@ export async function resolveOidcTrust({
302
305
  return { sub: 'repo:*', source: 'fallback' };
303
306
  }
304
307
 
305
- async function mainStackMain(input = {}) {
306
- const options = normalizeOptions(input);
307
- const { isHeadless = false } = options;
308
- const isPreconfigured = options.isPreconfigured === true || process.argv.includes('--preconfigured');
309
- const headlessOptions = normalizeOptions(options.headlessOptions);
310
- const initOptions = normalizeOptions(options.initOptions);
311
- const isInteractive = !isHeadless && !isPreconfigured;
312
- const startTime = Date.now();
313
-
314
- // 1. Silent Pre-flight check
315
- const hasTerraform = await checkDependency('terraform');
316
- if (!hasTerraform) {
317
- await failCommand({
318
- print: () => {
319
- console.error(color.red('✖ Terraform is not installed.'));
320
- console.log(color.yellow('Please run "npx grada-run doctor" to check your environment.'));
321
- },
322
- });
323
- }
324
-
325
- if (!isHeadless) intro(color.bgCyan(color.black(' grada ☁️ ')));
326
-
327
- // 2. Resolve Target & Scan Codebase
328
- const explicitProjectName = typeof initOptions.projectName === 'string' && initOptions.projectName.trim() !== ''
329
- ? initOptions.projectName.trim()
330
- : null;
331
- const explicitGitHubRepo = typeof initOptions.githubRepo === 'string' && initOptions.githubRepo.trim() !== ''
332
- ? initOptions.githubRepo.trim()
333
- : null;
334
- // Non-interactive wizard gate (sync-ai precedent: bespoke, not the
335
- // shared helper — approval flags cannot answer input questions, so
336
- // even `init --yes` must refuse here). Without --headless the wizard
337
- // always prompts (directory first), so an inferred-headless run (CI,
338
- // no TTY) could only abandon — refuse loudly instead. This sits
339
- // before the 2b flag validation below because the directory prompt
340
- // precedes it; re-running with --headless surfaces any specific
341
- // INVALID_* error. No preconfigured exemption: the parser only
342
- // exposes flag values in headless mode, so standalone
343
- // --preconfigured would silently ignore --framework/--region.
344
- if (!isHeadless && resolveHeadless(options)) {
345
- return failCommand({
346
- message: '\n✖ init needs an interactive terminal to gather project configuration.',
347
- hint: ' Re-run with --headless --framework <id> --target <ecs|lambda|static> (plus --region/--with as needed), or run interactively in a terminal.\n',
348
- event: 'project_provisioned',
349
- telemetry: { projectName: explicitProjectName ?? path.basename(process.cwd()) },
350
- errorCode: 'INIT_NON_INTERACTIVE',
351
- reason: 'non-interactive',
352
- exitCode: 1,
353
- });
354
- }
355
- const dirConfig = await getTargetDirectory(isHeadless, headlessOptions, { projectName: explicitProjectName });
308
+ // Step 9. Output: framework warnings, post-init hints, ORM notice, git
309
+ // instructions, and the offline checklist. Pure output — no state changes.
310
+ function printInitOutput({ isPreconfigured, config, detectedFramework, isInteractive, capabilities, target, migrationGateEnabled, migrationCmdSource, migrationCmd, dirConfig, offlineScaffold, procfile, stateBucketName, driftEnabled }) {
311
+ let frameworkWarnings = '';
356
312
 
357
- // Re-init over an existing tree keeps the tree's project name: after a
358
- // directory rename or copy, re-deriving from the basename would silently
359
- // fork every singleton (state bucket, RDS, ECR…) into a parallel stack
360
- // while the old one keeps billing. --project-name renames explicitly.
361
- const treeProjectName = readTerraformProjectName(dirConfig.targetDir);
362
- const sanitizedTreeName = treeProjectName ? sanitizeProjectName(treeProjectName) : null;
363
- if (sanitizedTreeName && explicitProjectName && sanitizedTreeName !== dirConfig.actualProjectName) {
364
- console.log(color.yellow(`⚠️ --project-name "${dirConfig.actualProjectName}" overrides this tree's project "${treeProjectName}" — the next apply will provision a NEW stack; the "${treeProjectName}" stack is left untouched (and still billing).`));
365
- trackEvent('init_project_name_override', { projectName: dirConfig.actualProjectName });
366
- } else if (sanitizedTreeName && !explicitProjectName && sanitizedTreeName !== dirConfig.actualProjectName) {
367
- console.log(color.yellow(`⚠️ Directory "${path.basename(dirConfig.targetDir)}" doesn't match this tree's project "${sanitizedTreeName}" — keeping "${sanitizedTreeName}" so re-init doesn't fork your infrastructure. Pass --project-name <name> to rename explicitly.`));
368
- trackEvent('init_project_name_reused', { projectName: sanitizedTreeName });
369
- dirConfig.actualProjectName = sanitizedTreeName;
313
+ if (!isPreconfigured && !(config.framework === 'static' && detectedFramework?.buildDir)) {
314
+ frameworkWarnings = getFrameworkWarning(config.framework);
370
315
  }
371
316
 
372
- // 2b. Fail-fast validation of init composition flags — before any
373
- // prompts, AWS calls, backups, or file writes.
374
- const explicitFramework = typeof headlessOptions.framework === 'string' && headlessOptions.framework.trim() !== ''
375
- ? headlessOptions.framework.trim()
376
- : null;
377
- if (explicitFramework !== null && !SUPPORTED_FRAMEWORKS.includes(explicitFramework)) {
378
- return failCommand({
379
- message: `\n✖ Unknown framework "${explicitFramework}".`,
380
- hint: ` Supported frameworks: ${SUPPORTED_FRAMEWORKS.join(', ')}.\n${explicitFramework === 'express' ? ' Express apps use --framework=node.\n' : ''}`,
381
- event: 'cli-error',
382
- telemetry: { step: 'init_validation', error_code: 'INVALID_FRAMEWORK' },
383
- reason: 'invalid-framework',
384
- });
385
- }
386
- if (explicitGitHubRepo !== null && !isValidGitHubRepoSlug(explicitGitHubRepo)) {
387
- return failCommand({
388
- message: `\n✖ Invalid --github-repo "${explicitGitHubRepo}".`,
389
- hint: ' Expected owner/name (e.g. --github-repo=acme/widgets).\n',
390
- event: 'cli-error',
391
- telemetry: { step: 'init_validation', error_code: 'INVALID_GITHUB_REPO' },
392
- reason: 'invalid-github-repo',
393
- });
394
- }
395
- const withList = Array.isArray(initOptions.with)
396
- ? initOptions.with.filter((cap) => typeof cap === 'string')
397
- : [];
398
- const unknownCaps = withList.filter((cap) => !ADDON_REGISTRY[cap]);
399
- if (unknownCaps.length > 0) {
400
- return failCommand({
401
- message: `\n✖ Unknown addon capabilities: ${unknownCaps.join(', ')}.`,
402
- hint: ` Valid capabilities: ${Object.keys(ADDON_REGISTRY).join(', ')}.\n`,
403
- event: 'cli-error',
404
- telemetry: { step: 'init_validation', error_code: 'UNSUPPORTED_CAPABILITY' },
405
- reason: 'unsupported-capability',
406
- resultExtra: { capabilities: withList },
407
- });
408
- }
409
- const VALID_DB_ENGINES = ['postgres', 'mysql', 'aurora-postgresql'];
410
- const explicitDbEngine = typeof initOptions.dbEngine === 'string' && initOptions.dbEngine.trim() !== ''
411
- ? initOptions.dbEngine.trim()
412
- : null;
413
- if (explicitDbEngine !== null && !VALID_DB_ENGINES.includes(explicitDbEngine)) {
414
- return failCommand({
415
- message: `\n✖ Invalid --db-engine "${explicitDbEngine}".`,
416
- hint: ` Valid engines: ${VALID_DB_ENGINES.join(', ')}.\n`,
417
- event: 'cli-error',
418
- telemetry: { step: 'init_validation', error_code: 'INVALID_DB_ENGINE' },
419
- reason: 'invalid-db-engine',
420
- });
421
- }
422
- const explicitTarget = typeof initOptions.target === 'string' && initOptions.target.trim() !== ''
423
- ? initOptions.target.trim()
424
- : null;
425
- const normalizedExplicitTarget = explicitTarget === 'fargate' ? 'ecs' : explicitTarget;
426
- if (explicitTarget !== null && !COMPUTE_TARGETS.includes(normalizedExplicitTarget)) {
427
- return failCommand({
428
- message: `\n✖ Invalid compute target "${explicitTarget}". Supported targets: ecs, lambda, static.`,
429
- hint: ' Use --target ecs (or fargate) for always-on containers, --target lambda for scale-to-zero serverless, or --target static for zero-compute S3 + CloudFront hosting.\n',
430
- event: 'cli-error',
431
- telemetry: { step: 'init_validation', error_code: 'INVALID_COMPUTE_TARGET' },
432
- reason: 'invalid-compute-target',
433
- });
434
- }
435
- const addonFlagOptions = {
436
- model: initOptions.model ?? undefined,
437
- domain: initOptions.domain ?? undefined,
438
- zoneId: initOptions.zoneId ?? undefined,
439
- fromEmail: initOptions.fromEmail ?? undefined,
440
- };
441
- for (const cap of withList) {
442
- // Per-capability scoped: irrelevant flags are silently ignored.
443
- const flagError = validateAddonFlags(cap, addonFlagOptions);
444
- if (flagError) {
445
- return failCommand({
446
- message: flagError.message,
447
- hint: flagError.hint ?? null,
448
- event: 'cli-error',
449
- telemetry: { step: 'init_validation', error_code: flagError.errorCode },
450
- reason: flagError.reason,
451
- resultExtra: { capability: cap },
452
- });
317
+ // 9b. Post-init capability hints (interactive only, so headless
318
+ // stdout stays byte-identical).
319
+ if (isInteractive) {
320
+ const upcoming = capabilities.upcomingHints;
321
+ if (upcoming.vector) {
322
+ console.log(color.dim(' 💡 Vector-search dependencies detected: managed pgvector support is coming soon.'));
453
323
  }
454
- }
455
- if (withList.includes('email:ses') && !isInteractive) {
456
- const hasDomainFlag = typeof initOptions.domain === 'string' && initOptions.domain.trim() !== '';
457
- let domainTfHasDomain = false;
458
- if (!hasDomainFlag) {
459
- const domainTf = readFileSafe(path.join(dirConfig.targetDir, 'terraform', 'domain.tf'));
460
- domainTfHasDomain = Boolean(domainTf && parseDomainTf(domainTf)?.domain);
324
+ // Static targets refuse `add cron` (no compute) — don't send
325
+ // static users down a dead end.
326
+ if (upcoming.cron && target !== 'static') {
327
+ console.log(color.dim(' 💡 Scheduled-task dependencies detected: scaffold a schedule with "grada add cron".'));
461
328
  }
462
- if (!hasDomainFlag && !domainTfHasDomain) {
463
- return failCommand({
464
- message: '\n✖ No domain for Amazon SES. Pass --domain <domain> or run from a project with terraform/domain.tf.\n',
465
- event: 'cli-error',
466
- telemetry: { step: 'init_validation', error_code: 'MISSING_SES_DOMAIN' },
467
- reason: 'missing-ses-domain',
468
- resultExtra: { capability: 'email:ses' },
469
- });
329
+ if (upcoming.mysql) {
330
+ console.log(color.dim(' 💡 MySQL dependencies detected: RDS currently provisions PostgreSQL; MySQL support is coming soon.'));
470
331
  }
471
332
  }
472
333
 
473
- // Collision suffix, resolved before any prompt/AWS call/write (and
474
- // before backup planning moves the old tree): fresh trees mint, re-init
475
- // reuses the rendered value, pre-suffix trees stay '' (zero drift).
476
- const resourceSuffix = resolveInitSuffix(dirConfig.targetDir);
477
-
478
- // Compute target: explicit flag wins (headless defaults to ECS);
479
- // interactive runs prompt when the flag was not passed.
480
- let target = normalizedExplicitTarget || 'ecs';
481
- if (isInteractive && normalizedExplicitTarget === null) {
482
- log.info(`${color.gray('📖 Compare tradeoffs (cost crossover, cold starts, DB connections):')} ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/architecture.md')}`);
483
- const targetAnswer = await select({
484
- message: 'Select your AWS compute target:',
485
- options: [
486
- { value: 'ecs', label: 'ECS Fargate + ALB', hint: 'Always-on, persistent DB connections, zero cold starts (Starts at ~$31/mo)' },
487
- { value: 'lambda', label: 'AWS Lambda + API Gateway v2', hint: 'Scale-to-zero, usage-based compute, 3-5s VPC cold starts ($0/mo idle)' },
488
- { value: 'static', label: 'Static site (S3 + CloudFront)', hint: 'Zero-compute hosting for SPAs/SSGs ($0/mo idle)' },
489
- ],
490
- });
491
- if (typeof targetAnswer === 'symbol') process.exit(0);
492
- target = targetAnswer;
493
- }
494
-
495
- // Capability-vs-target policy for --with: refuse fast when
496
- // the requested capability cannot render on this target (static has
497
- // no task role or VPC), before any prompt/AWS call/write. Interactive
498
- // multiselect offers only compatible targets' caps; this covers --with.
499
- for (const cap of withList) {
500
- if (!ADDON_REGISTRY[cap]) continue;
501
- if (addonTargetDisposition(cap, target) === 'refuse') {
502
- const targetGuard = guardComputeTarget({
503
- actual: target,
504
- command: `init --with ${cap}`,
505
- supported: addonSupportedTargets(cap),
506
- hint: 'Static sites run no containers — this capability needs a compute target (--target ecs or lambda).',
507
- });
508
- return failCommand({
509
- message: targetGuard.message,
510
- hint: targetGuard.hint,
511
- event: 'cli-error',
512
- telemetry: { step: 'init_validation', error_code: targetGuard.errorCode },
513
- reason: targetGuard.reason,
514
- resultExtra: { capability: cap },
515
- });
334
+ // ORM runner matrix: when the gate was auto-wired to a mapped ORM
335
+ // command, say which one and what the user must guarantee (the
336
+ // bundle path / production dependency), while the run is fresh.
337
+ if (migrationGateEnabled && migrationCmdSource === 'detected') {
338
+ const ormMapped = detectOrmMigrationCommand(dirConfig.targetDir);
339
+ if (ormMapped && ormMapped.command === migrationCmd) {
340
+ const ormWarning = ormMapped.orm === 'drizzle'
341
+ ? 'Detected Drizzle ORM. Configured migration gate to use \'node ./dist/migrate.cjs\'. Ensure your build script bundles your migrator to this path.'
342
+ : 'Detected Prisma. Configured migration gate to run via \'node_modules/prisma/build/index.js\'. Ensure Prisma is in your production dependencies.';
343
+ log.warn(color.yellow(`⚠️ ${ormWarning}`));
516
344
  }
517
345
  }
518
346
 
519
- const detectedFramework = detectFramework(dirConfig.targetDir);
520
- const procfile = parseProcfile(dirConfig.targetDir);
521
- const vercelRules = parseVercelConfig(dirConfig.targetDir);
522
- const dockerCompose = parseDockerCompose(dirConfig.targetDir);
523
- const capabilities = detectProjectCapabilities(dirConfig.targetDir);
347
+ const isGitInitialized = fsSync.existsSync(path.join(dirConfig.targetDir, '.git'));
348
+ const needsCd = dirConfig.projectName && dirConfig.projectName !== '.';
349
+ const applyStep = needsCd ? `cd ${dirConfig.projectName} && npx --yes grada-run apply` : 'npx --yes grada-run apply';
350
+ const gitInstructions = isGitInitialized
351
+ ? `git add . && git commit -m "chore: add AWS infrastructure and CI/CD" && git push`
352
+ : `git init && git add . && git commit -m "chore: add AWS infrastructure and CI/CD" && git branch -M ${config.branch} && git remote add origin https://github.com/your-username/your-repo.git && git push -u origin ${config.branch}`;
524
353
 
525
- if (!isHeadless) {
526
- if (detectedFramework) log.success(`Auto-detected framework: ${detectedFramework.name}`);
527
- if (procfile && procfile.web) log.success(`Auto-detected Procfile (web command: ${procfile.web.join(' ')})`);
528
- if (vercelRules) log.success(`Auto-detected vercel.json (Migrating edge network rules)`);
529
- if (dockerCompose) log.success(`Auto-detected docker-compose.yml (${dockerCompose.length} services mapped)`);
354
+ let docsTip = '';
355
+ if (procfile) {
356
+ docsTip = `\n ${color.blue('📘 Read the Heroku Migration Guide:')} ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/migrations/heroku-procfile-to-aws.md')}`;
357
+ } else if (config.needsDatabase) {
358
+ docsTip = `\n ${color.blue('📘 Read the Database Connections Guide:')} ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/database-connections.md')}`;
530
359
  }
531
360
 
532
- if (isHeadless) console.log(color.cyan(`🤖 Running grada in headless mode`));
361
+ outro(`${color.green('✅ Templates generated!')} ${color.blue('🛡️ DevSecOps scanning enabled.')}
362
+ ${frameworkWarnings ? `\n ${frameworkWarnings}` : ''}
363
+ ${color.yellow('Next steps:')}
364
+ 1. ${color.cyan(applyStep)}
365
+ 2. ${color.cyan(gitInstructions)}
366
+ ${color.magenta('🚀 Need help?')} ${color.underline('https://calendly.com/anton-codes-iac/15min')}${docsTip}`);
533
367
 
534
- // 3. Gather Configuration & Framework Quirks
535
- const config = await getProjectConfig(isHeadless, headlessOptions, dirConfig.targetDir, detectedFramework, { capabilities, dbEngine: explicitDbEngine, target });
536
- config.target = target;
368
+ if (offlineScaffold) {
369
+ // Pass the exact backend bucket (suffix included) — recomputing
370
+ // from the bare project name prints a bucket terraform never uses.
371
+ // Step 2 names only emitted workflows: preview/teardown render
372
+ // with PR previews, drift only when enabled.
373
+ printOfflineChecklist({
374
+ bucket: stateBucketName,
375
+ region: config.region,
376
+ workflows: [
377
+ 'deploy',
378
+ ...(config.enablePrPreviews ? ['preview', 'teardown'] : []),
379
+ ...(driftEnabled ? ['drift'] : []),
380
+ ],
381
+ });
382
+ }
383
+ }
537
384
 
538
- // 3a. Scope the GitHub OIDC trust (see resolveOidcTrust): explicit flag
539
- // wins, then the tree's rendered trust, then the git remote, then one
540
- // skippable prompt; headless falls through to the open trust — unless
541
- // that would widen a non-trivial existing claim, which refuses
542
- // (headless) or confirms (interactive). Telemetry records the mode
543
- // only — never the owner/repo.
544
- const oidcResolution = await resolveOidcTrust({
545
- explicitSlug: explicitGitHubRepo,
546
- treeClaim: readTerraformOidcTrust(dirConfig.targetDir),
547
- targetDir: dirConfig.targetDir,
548
- isInteractive,
549
- });
550
- if (oidcResolution.refusal) {
551
- return failCommand({ ...oidcResolution.refusal });
552
- }
553
- if (oidcResolution.cancelled) {
554
- cancel('Operation cancelled. Re-run with --github-repo owner/name to scope the trust explicitly.');
555
- process.exit(0);
385
+ // Step 8.5. Configure AI Context: per-assistant workspace rules. Advanced
386
+ // mode respects the explicit selection; quickstart auto-detects from the
387
+ // tree. Sync file writes only.
388
+ function configureAiRules({ targetDir, config }) {
389
+ const aiContext = { region: config.region, port: config.port, target: config.target };
390
+ const cwd = targetDir;
391
+
392
+ if (config.setupType === 'advanced') {
393
+ // --- ADVANCED MODE: Explicitly respect user choices ---
394
+ if (config.aiAssistants.includes('cursor')) {
395
+ const cursorDir = path.join(cwd, '.cursor', 'rules');
396
+ if (!fsSync.existsSync(cursorDir)) fsSync.mkdirSync(cursorDir, { recursive: true });
397
+ fsSync.writeFileSync(path.join(cursorDir, 'grada.mdc'), getCursorRules(aiContext));
398
+ }
399
+ if (config.aiAssistants.includes('roo')) {
400
+ const rooDir = path.join(cwd, '.roo', 'rules');
401
+ if (!fsSync.existsSync(rooDir)) fsSync.mkdirSync(rooDir, { recursive: true });
402
+ fsSync.writeFileSync(path.join(rooDir, 'grada.md'), getBaseRules(aiContext));
403
+ }
404
+ if (config.aiAssistants.includes('trae')) {
405
+ const traeDir = path.join(cwd, '.trae', 'rules');
406
+ if (!fsSync.existsSync(traeDir)) fsSync.mkdirSync(traeDir, { recursive: true });
407
+ injectManagedBlock(path.join(traeDir, 'project_rules.md'), getBaseRules(aiContext), true);
408
+ }
409
+ if (config.aiAssistants.includes('continue')) {
410
+ const promptsDir = path.join(cwd, '.prompts');
411
+ if (!fsSync.existsSync(promptsDir)) fsSync.mkdirSync(promptsDir, { recursive: true });
412
+ fsSync.writeFileSync(path.join(promptsDir, 'grada.prompt'), getBaseRules(aiContext));
413
+ }
414
+ if (config.aiAssistants.includes('windsurf')) {
415
+ injectManagedBlock(path.join(cwd, '.windsurfrules'), getBaseRules(aiContext), true);
416
+ }
417
+ if (config.aiAssistants.includes('copilot')) {
418
+ const copilotPath = path.join(cwd, '.github', 'copilot-instructions.md');
419
+ if (!fsSync.existsSync(path.dirname(copilotPath))) fsSync.mkdirSync(path.dirname(copilotPath), { recursive: true });
420
+ injectManagedBlock(copilotPath, getBaseRules(aiContext), true);
421
+ }
422
+ if (config.aiAssistants.includes('claude')) {
423
+ injectManagedBlock(path.join(cwd, 'CLAUDE.md'), getBaseRules(aiContext), true);
424
+ }
425
+ if (config.aiAssistants.includes('goose')) {
426
+ injectManagedBlock(path.join(cwd, '.goosehints'), getBaseRules(aiContext), true);
427
+ }
428
+ if (config.aiAssistants.includes('aider')) {
429
+ injectManagedBlock(path.join(cwd, '.aider.conf.yml'), getBaseRules(aiContext), false);
430
+ }
431
+ } else {
432
+ // --- QUICKSTART MODE: Silent Auto-Detection ---
433
+ if (fsSync.existsSync(path.join(cwd, '.cursor'))) {
434
+ const cursorDir = path.join(cwd, '.cursor', 'rules');
435
+ if (!fsSync.existsSync(cursorDir)) fsSync.mkdirSync(cursorDir, { recursive: true });
436
+ fsSync.writeFileSync(path.join(cursorDir, 'grada.mdc'), getCursorRules(aiContext));
437
+ }
438
+ if (fsSync.existsSync(path.join(cwd, '.roo')) || fsSync.existsSync(path.join(cwd, '.roorules'))) {
439
+ const rooDir = path.join(cwd, '.roo', 'rules');
440
+ if (!fsSync.existsSync(rooDir)) fsSync.mkdirSync(rooDir, { recursive: true });
441
+ fsSync.writeFileSync(path.join(rooDir, 'grada.md'), getBaseRules(aiContext));
442
+ }
443
+ if (fsSync.existsSync(path.join(cwd, '.trae'))) {
444
+ const traeDir = path.join(cwd, '.trae', 'rules');
445
+ if (!fsSync.existsSync(traeDir)) fsSync.mkdirSync(traeDir, { recursive: true });
446
+ injectManagedBlock(path.join(traeDir, 'project_rules.md'), getBaseRules(aiContext), true);
447
+ }
448
+ if (fsSync.existsSync(path.join(cwd, '.continue')) || fsSync.existsSync(path.join(cwd, '.prompts'))) {
449
+ const promptsDir = path.join(cwd, '.prompts');
450
+ if (!fsSync.existsSync(promptsDir)) fsSync.mkdirSync(promptsDir, { recursive: true });
451
+ fsSync.writeFileSync(path.join(promptsDir, 'grada.prompt'), getBaseRules(aiContext));
452
+ }
453
+ if (fsSync.existsSync(path.join(cwd, '.windsurf')) || fsSync.existsSync(path.join(cwd, '.windsurfrules'))) {
454
+ injectManagedBlock(path.join(cwd, '.windsurfrules'), getBaseRules(aiContext), true);
455
+ }
456
+
457
+ const copilotPath = path.join(cwd, '.github', 'copilot-instructions.md');
458
+ if (fsSync.existsSync(copilotPath)) injectManagedBlock(copilotPath, getBaseRules(aiContext), true);
459
+ if (fsSync.existsSync(path.join(cwd, 'CLAUDE.md'))) injectManagedBlock(path.join(cwd, 'CLAUDE.md'), getBaseRules(aiContext), true);
460
+ if (fsSync.existsSync(path.join(cwd, '.goosehints'))) injectManagedBlock(path.join(cwd, '.goosehints'), getBaseRules(aiContext), true);
461
+
462
+ if (fsSync.existsSync(path.join(cwd, '.aider.conf.yml'))) {
463
+ injectManagedBlock(path.join(cwd, '.aider.conf.yml'), getBaseRules(aiContext), false);
464
+ } else if (fsSync.existsSync(path.join(cwd, '.aider.model.settings.yml'))) {
465
+ injectManagedBlock(path.join(cwd, '.aider.model.settings.yml'), getBaseRules(aiContext), false);
466
+ }
556
467
  }
557
- const { sub: oidcTrustSub, source: oidcTrustSource } = oidcResolution;
558
- trackEvent('init_oidc_trust', {
559
- projectName: dirConfig.actualProjectName,
560
- mode: oidcTrustSub === 'repo:*' ? 'fallback' : 'scoped',
561
- source: oidcTrustSource,
468
+ }
469
+
470
+ // Step 8. Telemetry: the project_provisioned funnel event. Identifiers
471
+ // stay out — names, counts, and modes only.
472
+ function trackProvisionedTelemetry({ projectName, isHeadless, startTime, target, config, resourceSuffix, detectedFramework, willHaveWorker, procfile, vercelRules, dockerCompose, capabilities, selectedAddons, migrationGateEnabled, driftEnabled, planEnabled }) {
473
+ trackEvent('project_provisioned', {
474
+ // 1. Core & Context
475
+ projectName,
476
+ success: true, // funnel outcome: failures emit success:false via failCommand
477
+ cli_version: CLI_VERSION,
478
+ is_headless: isHeadless,
479
+ setup_mode: config.setupType,
480
+ duration_ms: Date.now() - startTime,
481
+
482
+ // 2. Infrastructure Shape
483
+ target,
484
+ framework: config.framework,
485
+ resource_suffix_present: resourceSuffix !== '',
486
+ specific_framework: detectedFramework?.name || config.framework,
487
+ region: config.region,
488
+ size: config.size,
489
+ desired_count: parseInt(config.desiredCount),
490
+ has_database: config.needsDatabase,
491
+ db_engine: config.needsDatabase ? config.dbEngine : 'none',
492
+ has_custom_health_check: config.healthCheckPath !== '/',
493
+
494
+ // 3. Advanced Features & PaaS Context
495
+ has_worker: willHaveWorker,
496
+ is_heroku_migration: !!procfile,
497
+ is_vercel_migration: !!vercelRules,
498
+ is_docker_compose: !!dockerCompose,
499
+ has_pr_previews: config.enablePrPreviews,
500
+ ai_assistants_configured: config.aiAssistants || [],
501
+
502
+ // 4. Dependency-aware composition
503
+ selected_addons: selectedAddons,
504
+ detected_addons: Object.keys(ADDON_REGISTRY).filter((cap) => capabilities.addons[cap]?.detected === true),
505
+ migration_gate_enabled: migrationGateEnabled,
506
+ drift_detection_enabled: driftEnabled,
507
+ plan_on_pr_enabled: planEnabled,
562
508
  });
563
- // Explicit flag wins everywhere (headless defaults to postgres, the
564
- // interactive prompt is skipped); anything else falls back to postgres.
565
- if (explicitDbEngine) {
566
- config.dbEngine = explicitDbEngine;
567
- } else if (!VALID_DB_ENGINES.includes(config.dbEngine)) {
568
- config.dbEngine = 'postgres';
569
- }
570
- const djangoWsgi = await resolveDjangoWsgi(dirConfig.targetDir, procfile, config.framework, isHeadless);
571
- const disableDefaultCI = await handleRailsCI(dirConfig.targetDir, config.framework, isHeadless, { force: initOptions.force === true });
509
+ }
572
510
 
573
- // 3b. Dependency-aware composition (worker, migration gate, addons).
574
- // Everything here resolves before backups, AWS calls, or file writes.
575
- const isStaticSite = config.framework === 'static';
576
- // Static exports (Next.js output:'export', SvelteKit adapter-static)
577
- // carry no server, so --target static admits them like static presets.
578
- // This extends only the gate — prompts.js still resolves the container
579
- // preset from the detected id on ecs/lambda.
580
- const isStaticExport = detectedFramework?.isStaticExport === true;
581
- if (target === 'static' && !isStaticSite && !isStaticExport) {
582
- return failCommand({
583
- message: `\n✖ --target static only supports static-site frameworks (detected: ${config.framework}).\n`,
584
- hint: ' Use --target ecs for containerized apps or --target lambda for scale-to-zero serverless.\n',
585
- event: 'cli-error',
586
- telemetry: { step: 'init_validation', error_code: 'STATIC_TARGET_FRAMEWORK_MISMATCH' },
587
- reason: 'static-target-framework-mismatch',
588
- resultExtra: { framework: config.framework },
589
- });
590
- }
591
- if (target === 'static' && (procfile?.worker || capabilities.worker.detected)) {
592
- log.warn(color.yellow('⚠️ Skipping the background worker: static targets serve files from S3 + CloudFront with no compute to run it on.'));
511
+ // Steps 7b2 + 7c. Restore preserved files over the fresh output, record
512
+ // the init manifest, and print the addon stack preview. Runs after every
513
+ // generator above so hashes cover the final tree.
514
+ async function finalizeInitTree({ dirConfig, target, preservedStash, selectedAddons, detectedFramework, config }) {
515
+ // 7b2. Restore preserved files over the fresh output, then record
516
+ // content hashes of everything generated above so a later re-run can
517
+ // distinguish pristine output from hand edits (F3), plus the intended
518
+ // compute target (R5) for the target-switch gate. The manifest lands
519
+ // after the restore so secret_keys.json hashes the carried content.
520
+ restoreManagedFiles(dirConfig.targetDir, preservedStash);
521
+ writeInitManifest(dirConfig.targetDir, { target });
522
+
523
+ // 7c. Print-only stack preview when addons were scaffolded (default
524
+ // no-addon output is untouched).
525
+ if (selectedAddons.length > 0) {
526
+ const parsed = parseTerraformConfig(path.join(dirConfig.targetDir, 'terraform'));
527
+ parsed.projectName = dirConfig.actualProjectName;
528
+ parsed.framework = detectedFramework?.name || config.framework;
529
+ await renderDryRunPreview(parsed, true);
593
530
  }
594
- if (target === 'static' && config.needsDatabase) {
595
- log.warn(color.yellow('⚠️ Skipping the database: static targets have no compute to connect from. Provision data separately if the site needs an API.'));
596
- config.needsDatabase = false;
531
+ }
532
+
533
+ // Step 7b. Scaffold selected addons (registry order), then wire the
534
+ // pre-deploy migration gate plus the drift + plan workflows.
535
+ async function wireInitWorkflows({ targetDir, projectName, resourceSuffix, region, dbEngine, awsAccountId, selectedAddons, resolvedByCap, migrationGateEnabled, migrationCmd, target, driftEnabled, planEnabled, force }) {
536
+ for (const cap of selectedAddons) {
537
+ const scaffolded = await scaffoldAddon(cap, resolvedByCap[cap], { cwd: targetDir, region });
538
+ console.log(color.green(`✅ Scaffolded terraform/${scaffolded.file} (${cap})`));
597
539
  }
598
- const failAddonResolution = (cap, resolved) => {
599
- if (!resolved.ok && resolved.cancelled) {
600
- return failCommand({
601
- print: () => cancel('Selection cancelled.'),
602
- event: 'cli-error',
603
- telemetry: { step: 'init_addons', reason: 'cancelled' },
604
- reason: 'cancelled',
605
- exitCode: null,
606
- });
540
+
541
+ if (migrationGateEnabled && migrationCmd) {
542
+ const deployYmlPath = path.join(targetDir, '.github', 'workflows', 'deploy.yml');
543
+ const workflowContent = readFileSafe(deployYmlPath);
544
+ // Scope the gate's snapshot id to the database (aurora
545
+ // takes the cluster prefix) so guardrails and gc can name it.
546
+ const gateDbRefs = resolveDbEngineRefs(dbEngine);
547
+ const gateDbIdentifier = `${projectName}${resourceSuffix}-db${gateDbRefs.isCluster ? '-cluster' : ''}`;
548
+ const gated = workflowContent ? injectMigrationGate(workflowContent, { cmd: migrationCmd, cliVersion: CLI_VERSION, dbIdentifier: gateDbIdentifier }) : null;
549
+ if (gated) {
550
+ atomicWriteFileSync(deployYmlPath, gated);
551
+ console.log(color.green('✅ Wired the pre-deploy database migration gate into .github/workflows/deploy.yml (snapshot first, then migrate)'));
552
+ } else {
553
+ log.warn(color.yellow('⚠️ Could not wire the migration gate: the deploy workflow anchor was not found.'));
607
554
  }
608
- return failCommand({
609
- message: resolved.message,
610
- hint: resolved.hint ?? null,
611
- event: 'cli-error',
612
- telemetry: { step: 'init_addons', error_code: resolved.errorCode },
613
- reason: resolved.reason,
614
- resultExtra: { capability: cap },
615
- });
616
- };
555
+ if (target === 'ecs') {
556
+ const previewYmlPath = path.join(targetDir, '.github', 'workflows', 'preview.yml');
557
+ const previewContent = readFileSafe(previewYmlPath);
558
+ if (previewContent) {
559
+ const previewGated = injectPreviewMigrationGate(previewContent, { cmd: migrationCmd, cliVersion: CLI_VERSION });
560
+ if (previewGated) {
561
+ atomicWriteFileSync(previewYmlPath, previewGated);
562
+ console.log(color.green('✅ Wired the preview database migration gate into .github/workflows/preview.yml'));
563
+ } else {
564
+ log.warn(color.yellow('⚠️ Could not wire the preview migration gate: the Comment PR anchor was not found.'));
565
+ }
566
+ }
567
+ }
568
+ }
617
569
 
618
- // Worker command: Procfile-driven as before, plus detection-driven.
619
- // Lambda targets have no ECS worker service, so the prompt is skipped
620
- // and any Procfile worker process is left out of the generated stack.
621
- let workerCommandHcl = '';
622
- if (isInteractive && !isStaticSite && target !== 'lambda' && target !== 'static' && (procfile?.worker || capabilities.worker.detected)) {
623
- const workerAnswer = await promptWorkerCommand(procfile, capabilities);
624
- if (workerAnswer.trim() !== '') {
625
- workerCommandHcl = `command = ${toHclStringArray(splitProcfileCommand(workerAnswer.trim()))}`;
570
+ if (driftEnabled) {
571
+ // drift.yml rides the manifest + backup like deploy.yml now
572
+ // Re-init backs the old file up and regenerates fresh
573
+ // (current role ARN) instead of silently keeping a stale copy.
574
+ // Hand edits trip refuse-dirty before this point; --force regenerates.
575
+ const drifted = scaffoldDriftWorkflow(targetDir, {
576
+ region,
577
+ roleArn: buildRoleArn(awsAccountId, buildDeployRoleName(projectName, resourceSuffix)),
578
+ force,
579
+ });
580
+ if (drifted.ok) {
581
+ console.log(color.green('✅ Scaffolded .github/workflows/drift.yml (scheduled IaC drift detection)'));
626
582
  }
627
583
  }
628
- if (!isInteractive && !isStaticSite && target !== 'lambda' && target !== 'static' && !procfile?.worker && capabilities.worker.detected) {
629
- // The suggested command is an npm shim (broken on stripped
630
- // runners), so headless never scaffolds it blindly — but the
631
- // detection must not vanish silently either.
632
- const evidence = (capabilities.worker.evidence || []).join(', ') || 'worker signals';
633
- const suggested = capabilities.worker.suggestedCommand || 'none';
634
- log.warn(color.yellow(`⚠️ Skipping the background worker: detection found ${evidence} but no Procfile worker process, and the suggested command ("${suggested}") needs interactive confirmation. Re-run init interactively to configure the worker command.`));
584
+
585
+ if (planEnabled) {
586
+ // plan.yml rides the manifest + backup like drift.yml (R1):
587
+ // re-init backs the old file up and regenerates fresh (current
588
+ // role ARN) instead of silently keeping a stale copy.
589
+ const planned = scaffoldPlanWorkflow(targetDir, {
590
+ region,
591
+ roleArn: buildRoleArn(awsAccountId, buildPreviewRoleName(projectName, resourceSuffix)),
592
+ force,
593
+ });
594
+ if (planned.ok) {
595
+ console.log(color.green('✅ Scaffolded .github/workflows/plan.yml (Terraform plan on PR)'));
596
+ }
635
597
  }
636
- if (target === 'lambda' && (procfile?.worker || capabilities.worker.detected)) {
637
- log.warn(color.yellow('⚠️ Skipping the background worker: Lambda targets run a single scale-to-zero function with no ECS worker service.'));
598
+ }
599
+
600
+ // Step 7. Synthesize Templates: branch resolution, render-config assembly,
601
+ // template generation, and the compose-secrets telemetry note.
602
+ async function synthesizeInitTemplates({ dirConfig, config, target, resourceSuffix, cpu, memory, computeTier, estimatedCost, buildDir, stateBucketName, awsAccountId, djangoWsgi, disableDefaultCI, procfile, vercelRules, composeForMerge, composeWebName, workerCommandHcl, oidcTrustSub, oidcTreeBranches }) {
603
+ // Live origin/HEAD wins when it names a real branch; when
604
+ // detection falls back, a re-init keeps the tree's own default branch
605
+ // so dual trust never narrows silently.
606
+ const treeDefaultBranch = oidcTreeBranches?.[1] ?? null;
607
+ const detectedDefaultBranch = resolveDefaultBranch(dirConfig.targetDir, config.branch);
608
+ const defaultBranch = detectedDefaultBranch !== config.branch
609
+ ? detectedDefaultBranch
610
+ : (treeDefaultBranch ?? config.branch);
611
+ if (defaultBranch !== config.branch && treeDefaultBranch === null) {
612
+ log(color.yellow(`⚠️ Trusting default branch "${defaultBranch}" alongside deploy branch "${config.branch}" so scheduled drift can assume the deploy role.`));
638
613
  }
639
- if (target === 'lambda' && config.needsDatabase) {
640
- log.warn(color.yellow('⚠️ Lambda opens a database connection per concurrent execution with no proxy in between — bursts can exhaust RDS limits. Keep pools tiny (tradeoffs: https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/architecture.md#fargate-vs-lambda-tradeoffs).'));
614
+ const { deploySub, previewSub } = renderOidcRoleSubs(oidcTrustSub, config.branch, defaultBranch);
615
+ const renderConfig = {
616
+ PROJECT_NAME: dirConfig.actualProjectName,
617
+ RESOURCE_SUFFIX: resourceSuffix,
618
+ REGION: config.region,
619
+ PORT: config.port,
620
+ CPU: cpu,
621
+ MEMORY: memory,
622
+ COMPUTE_TIER: computeTier,
623
+ ESTIMATED_COST: estimatedCost,
624
+ STATE_BUCKET: stateBucketName,
625
+ AWS_ACCOUNT_ID: awsAccountId,
626
+ HEALTH_CHECK_PATH: config.healthCheckPath,
627
+ DESIRED_COUNT: config.desiredCount,
628
+ DEPLOY_BRANCH: config.branch,
629
+ DEPLOY_ROLE_NAME: buildDeployRoleName(dirConfig.actualProjectName, resourceSuffix),
630
+ PREVIEW_ROLE_NAME: buildPreviewRoleName(dirConfig.actualProjectName, resourceSuffix),
631
+ GITHUB_DEPLOY_SUB: deploySub,
632
+ GITHUB_PREVIEW_SUB: previewSub,
633
+ BUILD_DIR: buildDir,
634
+ finalFramework: config.framework,
635
+ NEEDS_DATABASE: config.needsDatabase,
636
+ DB_ENGINE: config.dbEngine,
637
+ DJANGO_WSGI: djangoWsgi,
638
+ DISABLE_DEFAULT_CI: disableDefaultCI,
639
+ PROCFILE: procfile,
640
+ VERCEL_RULES: vercelRules,
641
+ DOCKER_COMPOSE: composeForMerge,
642
+ DOCKER_COMPOSE_WEB: composeWebName,
643
+ ENABLE_PR_PREVIEWS: config.enablePrPreviews,
644
+ WORKER_COMMAND: workerCommandHcl,
645
+ TARGET: target
646
+ };
647
+ await generateTemplates(dirConfig.targetDir, renderConfig);
648
+ if (Array.isArray(renderConfig.COMPOSE_SECRETS_FILTERED) && renderConfig.COMPOSE_SECRETS_FILTERED.length > 0) {
649
+ trackEvent('compose_secrets_filtered', {
650
+ projectName: dirConfig.actualProjectName,
651
+ count: renderConfig.COMPOSE_SECRETS_FILTERED.length,
652
+ names: renderConfig.COMPOSE_SECRETS_FILTERED,
653
+ });
641
654
  }
642
- const willHaveWorker = target !== 'lambda' && target !== 'static' && (Boolean(procfile?.worker) || workerCommandHcl !== '');
655
+ }
643
656
 
644
- // Pre-deploy migration gate: explicit flag wins, else prompt. An
645
- // explicit --setup-ci-migrate=<cmd> overrides detection, which is the
646
- // escape hatch when detection yields an npm shim on a stripped runner.
647
- const setupCiMigrateOpt = initOptions.setupCiMigrate;
648
- const explicitMigrationCmd = typeof setupCiMigrateOpt === 'string' && setupCiMigrateOpt.trim() !== ''
649
- ? setupCiMigrateOpt.trim()
650
- : null;
651
- const setupCiMigrateFlag = setupCiMigrateOpt === true || typeof setupCiMigrateOpt === 'string';
652
- const migrationCmd = explicitMigrationCmd || capabilities.migration.command;
653
- const migrationCmdSource = explicitMigrationCmd ? 'explicit' : 'detected';
654
- let migrationGateEnabled = false;
655
- if ((target === 'lambda' || target === 'static') && (setupCiMigrateFlag || (config.needsDatabase && migrationCmd))) {
656
- log.warn(color.yellow(`⚠️ Skipping the pre-deploy migration gate: it runs migrations as an ephemeral ECS task, which ${target === 'static' ? 'static' : 'Lambda'} targets don't provision. Run migrations from CI against your database endpoint instead.`));
657
- } else if (config.needsDatabase && migrationCmd) {
658
- if (setupCiMigrateFlag) {
659
- migrationGateEnabled = true;
660
- } else if (isInteractive) {
661
- const gateAnswer = await confirm({
662
- message: `Enable pre-deploy database migration gate in GitHub Actions? (${migrationCmdSource}: ${migrationCmd})`,
663
- initialValue: true,
657
+ // Step 6a. Plan existing-file handling BEFORE provisioning: headless
658
+ // fail paths fire here while the tree is still intact, and the actual
659
+ // renames wait until provisioning succeeds. Returns the plan plus the
660
+ // preserved-files stash, or { refusal }.
661
+ async function planInitFileHandling({ targetDir, isHeadless, force }) {
662
+ const existingFilesPlan = await planExistingFiles(targetDir, { isHeadless, force });
663
+ const existingFilesRefusal = await refusalResultForPlan(existingFilesPlan);
664
+ if (existingFilesRefusal) return { refusal: existingFilesRefusal };
665
+ // Stash preserved files before anything mutates the tree; the stash is
666
+ // discarded untouched when provisioning fails below.
667
+ const preservedStash = preserveManagedFiles(targetDir);
668
+ return { existingFilesPlan, preservedStash };
669
+ }
670
+
671
+ // Step 6b. Provision remote state (or scaffold offline placeholders),
672
+ // run the state-adoption gate, and move the old tree aside. Returns the
673
+ // bucket ids, or { refusal }.
674
+ async function provisionInitState({ s, initOptions, isHeadless, targetDir, projectName, resourceSuffix, region, existingFilesPlan, offlineScaffold }) {
675
+ let awsAccountId;
676
+ let stateBucketName;
677
+ let adoptionRefusal = null;
678
+ try {
679
+ if (offlineScaffold) {
680
+ // Scaffold-only mode for template development and CI
681
+ // fixtures — no AWS calls. Placeholders are greppable and
682
+ // invalid as real values (uppercase), so an unreconciled tree
683
+ // fails loud at `terraform init` instead of half-working.
684
+ awsAccountId = OFFLINE_ACCOUNT_PLACEHOLDER;
685
+ stateBucketName = formatStateBucketName(`${projectName}${resourceSuffix}`, OFFLINE_ACCOUNT_PLACEHOLDER);
686
+ s.stop('Offline mode: skipping state bucket provisioning.');
687
+ trackEvent('init_offline_scaffold', { projectName });
688
+ } else {
689
+ const bucketData = await provisionStateBucket(region, `${projectName}${resourceSuffix}`);
690
+ awsAccountId = bucketData.awsAccountId;
691
+ stateBucketName = bucketData.stateBucketName;
692
+ // Adoption gate: a fresh tree pointing at a bucket that already
693
+ // holds state needs an explicit adopt/rename/wipe choice before
694
+ // anything touches the tree. Probe failures fail closed through
695
+ // the provisioning catch below.
696
+ const isFreshTree = existingFilesPlan.decision === 'clean' && existingFilesPlan.foundFiles.length === 0;
697
+ // An interactive prompt may fire below: park the spinner first
698
+ // so it doesn't scribble over the choice (precedent: apply's
699
+ // recovery prompt). Headless runs never prompt.
700
+ const mayPromptAdoption = !isHeadless && initOptions.adoptState !== true && isFreshTree;
701
+ if (mayPromptAdoption) s.stop('State bucket ready.');
702
+ adoptionRefusal = await checkStateAdoption({
703
+ s3: bucketData.s3Client ?? null,
704
+ bucket: stateBucketName,
705
+ isFreshTree,
706
+ isHeadless,
707
+ adoptState: initOptions.adoptState === true,
664
708
  });
665
- if (typeof gateAnswer === 'symbol') process.exit(0);
666
- migrationGateEnabled = gateAnswer === true;
709
+ if (mayPromptAdoption && !adoptionRefusal) s.start('Provisioning infrastructure...');
667
710
  }
668
- } else if (setupCiMigrateFlag) {
669
- log.warn(color.yellow('⚠️ --setup-ci-migrate was passed but no database is configured or no migration command was given; skipping the migration gate.'));
711
+ } catch (error) {
712
+ s.stop('❌ Failed to provision remote state or authenticate with AWS.');
713
+ trackEvent('init_backup_deferred', {
714
+ projectName,
715
+ plan: existingFilesPlan.decision,
716
+ });
717
+ // Auth failures print the shared credential-recovery guidance;
718
+ // init keeps its own telemetry + exit path through failCommand.
719
+ if (isAuthError(error)) printAwsAuthGuidance(initOptions);
720
+ return {
721
+ refusal: await failCommand({
722
+ message: `AWS Error: ${error.message}`,
723
+ useErrorStream: true,
724
+ event: 'cli-error',
725
+ telemetry: { step: 'aws_provisioning', error_code: error.name || 'UNKNOWN', error_message: error.message },
726
+ }),
727
+ };
670
728
  }
729
+ if (adoptionRefusal) return { refusal: await failCommand(adoptionRefusal) };
671
730
 
672
- // Stripped-runner guard: init is about to generate a node
673
- // Dockerfile without npm/npx, so wiring an npm-shim command into the
674
- // gate would fail 100% of deploys. Fail fast headless (re-run with an
675
- // explicit node command); warn loudly interactively and continue.
676
- if (migrationGateEnabled && isNpmShimCommand(migrationCmd) && target === 'ecs' && frameworkUsesStrippedRunner(config.framework)) {
677
- const ormHint = ormMappedHintSegment(dirConfig.targetDir, '--setup-ci-migrate=');
678
- if (!isInteractive) {
679
- return failCommand({
680
- message: `\n✖ Refusing to wire the pre-deploy migration gate with "${migrationCmd}": the generated ${config.framework} Dockerfile strips npm/npx from the runner image, so this command would fail with "command not found" on every deploy.\n`,
681
- hint: ` Re-run with an explicit node-based command, e.g. \`--setup-ci-migrate="node ./dist/migrate.cjs"\`, or wire the gate later with \`grada db migrate --cmd "node ./dist/migrate.cjs" --setup-ci\`. Ensure your Dockerfile builds the bundle and copies it into the runner image${ormHint}.\n`,
682
- event: 'cli-error',
683
- telemetry: { step: 'init_setup', cmd_source: migrationCmdSource, error_code: 'NPM_CMD_STRIPPED_RUNNER' },
684
- errorCode: 'NPM_CMD_STRIPPED_RUNNER',
685
- reason: 'npm-cmd-stripped-runner',
686
- });
731
+ // Provisioning succeeded: move the old tree aside (no-op on a clean
732
+ // slate), then regenerate over the cleared ground.
733
+ await executeBackup(targetDir, existingFilesPlan);
734
+ return { awsAccountId, stateBucketName };
735
+ }
736
+
737
+ // Step 5. Calculate Derived Values: sizing, cost estimate, build dir.
738
+ // Pure computation over the resolved config.
739
+ function deriveInitValues({ config, willHaveWorker, target, selectedAddons, detectedFramework }) {
740
+ const cpu = config.size === 'small' ? '512' : '256';
741
+ const memory = config.size === 'small' ? '1024' : '512';
742
+ const computeTier = config.size === 'small' ? 'Small (0.5 vCPU, 1GB RAM)' : 'Micro (0.25 vCPU, 512MB RAM)';
743
+
744
+ const costs = estimateMonthlyCost({
745
+ cpu: parseInt(cpu),
746
+ memory: parseInt(memory),
747
+ hasDb: config.needsDatabase,
748
+ dbEngine: config.dbEngine,
749
+ hasWorker: willHaveWorker,
750
+ hasSecrets: target !== 'static',
751
+ addons: selectedAddons,
752
+ computeTarget: target,
753
+ });
754
+ const estimatedCost = costs.totalMonthly;
755
+ const buildDir = detectedFramework?.buildDir || 'dist';
756
+ return { cpu, memory, computeTier, estimatedCost, buildDir };
757
+ }
758
+
759
+ // Step 4. Framework Migration Checks (Vercel Escape Hatch): dropped
760
+ // edge rules plus per-framework adapter warnings. Pure output.
761
+ function warnMigrationMismatches({ target, vercelRules, config, detectedFramework, targetDir }) {
762
+ if ((target === 'lambda' || target === 'static') && vercelRules?.redirects?.length > 0) {
763
+ const remedy = target === 'static'
764
+ ? 'Recreate them as CloudFront Functions after provisioning.'
765
+ : 'Recreate them as API Gateway routes after provisioning.';
766
+ log.warn(color.yellow(`⚠️ vercel.json redirects were detected, but ${target === 'static' ? 'static' : 'Lambda'} targets have no ALB listener rules to translate them into. ${remedy}`));
767
+ }
768
+
769
+ // Headers/rewrites have no translator on any target — name the dropped
770
+ // counts loudly, or the "Migrating edge network rules" success line
771
+ // reads as if everything migrated.
772
+ {
773
+ const migratedRedirects = (target === 'lambda' || target === 'static') ? 0 : (vercelRules?.redirects?.length || 0);
774
+ const droppedHeaders = vercelRules?.headers?.length || 0;
775
+ const droppedRewrites = vercelRules?.rewrites?.length || 0;
776
+ if (droppedHeaders > 0 || droppedRewrites > 0) {
777
+ const dropped = [
778
+ droppedHeaders > 0 ? `${droppedHeaders} header rule${droppedHeaders === 1 ? '' : 's'}` : null,
779
+ droppedRewrites > 0 ? `${droppedRewrites} rewrite${droppedRewrites === 1 ? '' : 's'}` : null,
780
+ ].filter(Boolean).join(' and ');
781
+ log.warn(color.yellow(`⚠️ vercel.json ${dropped} were detected but are not migrated (only redirects translate to ALB listener rules — ${migratedRedirects} migrated). Recreate them as CloudFront Functions or ALB listener rules after provisioning.`));
687
782
  }
688
- console.log(color.yellow(`⚠️ The ${migrationCmdSource} migration command ("${migrationCmd}") starts with npm/npx but the generated ${config.framework} Dockerfile strips those binaries from the runner image — the gate will fail unless you switch to a node-based command (e.g. "node ./dist/migrate.cjs"). Ensure your Dockerfile builds the bundle and copies it into the runner image.${ormHint}`));
689
- trackEvent('npm_cmd_stripped_runner', { projectName: dirConfig.actualProjectName, cmd_source: migrationCmdSource, ci_setup: true });
690
783
  }
691
784
 
692
- // Scheduled IaC drift detection: explicit flag wins, else offer.
693
- // Opt-in by default — the workflow opens GitHub Issues on its own.
694
- const setupCiDriftFlag = initOptions.setupCiDrift === true;
695
- let driftEnabled = false;
696
- if (setupCiDriftFlag) {
697
- driftEnabled = true;
698
- } else if (isInteractive) {
699
- const driftAnswer = await confirm({
700
- message: 'Set up scheduled IaC drift detection (daily terraform plan + GitHub Issues)?',
701
- initialValue: false,
702
- });
703
- if (typeof driftAnswer === 'symbol') process.exit(0);
704
- driftEnabled = driftAnswer === true;
785
+ if (config.framework === 'nestjs') {
786
+ const nestAnalysis = analyzeNestApp(targetDir);
787
+ if (nestAnalysis.hasMain && !nestAnalysis.listensOnAllInterfaces) {
788
+ log.warn(color.yellow(`⚠️ NestJS must listen on 0.0.0.0 to receive traffic in ${target === 'lambda' ? 'AWS Lambda' : 'AWS Fargate'}.`));
789
+ console.log(color.cyan(` In ${nestAnalysis.filePath}, update your bootstrap:`));
790
+ console.log(color.green(` await app.listen(process.env.PORT ?? 3000, '0.0.0.0');\n`));
791
+ }
792
+ } else if (config.framework === 'nextjs') {
793
+ const nextConfig = analyzeNextConfig(targetDir);
794
+ // Static exports need no container, so the standalone warning
795
+ // (container-image slimming) does not apply to them.
796
+ if (nextConfig.hasConfig && !nextConfig.isStandalone && !nextConfig.isExport) {
797
+ log.warn(color.yellow('⚠️ Next.js config is missing "output: \'standalone\'".'));
798
+ console.log(color.cyan(' Fix it here: https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/migrations/nextjs-vercel-to-aws.md'));
799
+ }
800
+ } else if (detectedFramework?.id === 'svelte') {
801
+ const svelteConfig = analyzeSvelteConfig(targetDir);
802
+ if (svelteConfig.adapter === 'vercel' || svelteConfig.adapter === 'auto') {
803
+ log.warn(color.yellow('⚠️ SvelteKit is locked into the Vercel/Auto adapter.'));
804
+ console.log(color.cyan(' Fix it here: https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/migrations/sveltekit-vercel-to-aws.md'));
805
+ }
806
+ } else if (detectedFramework?.name === 'Astro') {
807
+ const astroConfig = analyzeAstroConfig(targetDir);
808
+ if (astroConfig.adapter === 'vercel') {
809
+ log.warn(color.yellow('⚠️ Astro is locked into the Vercel adapter.'));
810
+ console.log(color.cyan(' Fix it here: https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/migrations/astro-vercel-to-aws.md'));
811
+ }
705
812
  }
813
+ }
706
814
 
707
- // Plan-on-PR: explicit flag wins, else offer. Defaults ON —
708
- // reviewing infra changes before merge is the safe default.
709
- const setupCiPlanFlag = initOptions.setupCiPlan === true;
710
- let planEnabled = false;
711
- if (setupCiPlanFlag) {
712
- planEnabled = true;
713
- } else if (isInteractive) {
714
- const planAnswer = await confirm({
715
- message: 'Post Terraform plans as PR comments (review infra changes before merge)?',
716
- initialValue: true,
815
+ // Step 3.5. Docker Compose Overrides. The web service is the `build:`
816
+ // service first, then the framework-port match, then the first
817
+ // non-datastore service — never an anointed database. A
818
+ // datastore-only file skips the merge (and the port override) with a
819
+ // loud warning in both modes; the selection passes through to the
820
+ // generator so it merges without re-warning. May override config.port.
821
+ function mergeComposeOverrides({ dockerCompose, config, projectName, isHeadless }) {
822
+ let composeForMerge = dockerCompose;
823
+ let composeWebName = null;
824
+ if (dockerCompose && dockerCompose.length > 0) {
825
+ const selection = selectComposeWebService(dockerCompose, {
826
+ frameworkPort: frameworkDefaultPort(config.framework),
717
827
  });
718
- if (typeof planAnswer === 'symbol') process.exit(0);
719
- planEnabled = planAnswer === true;
828
+ if (!selection.service) {
829
+ console.log(color.yellow('⚠️ No app service detected in your compose file (every service looks like a datastore) — skipping the compose merge. Give your app service a `build:` key and re-run to merge it.'));
830
+ trackEvent('compose_merge_skipped', { projectName, reason: selection.skipped });
831
+ composeForMerge = null;
832
+ } else {
833
+ composeWebName = selection.service.name;
834
+ if (selection.datastoreImage) {
835
+ console.log(color.yellow(`⚠️ Compose service "${selection.service.name}" looks like a datastore but was selected as the web service — verify the merged port and env vars before applying.`));
836
+ trackEvent('compose_datastore_web_warned', { projectName, service: selection.service.name });
837
+ }
838
+ if (selection.service.port) {
839
+ // Override the config port with the one from Docker Compose
840
+ config.port = selection.service.port.toString();
841
+ if (!isHeadless) {
842
+ console.log(color.cyan(` 🐳 Docker Compose overrides: Port set to ${config.port} via service "${selection.service.name}"`));
843
+ }
844
+ }
845
+ }
720
846
  }
847
+ return { composeForMerge, composeWebName };
848
+ }
849
+
850
+ // Step 3b (addons). Addon selection (interactive multiselect or explicit
851
+ // --with) plus per-addon option resolution. Returns the registry-ordered
852
+ // selection with resolved configs, or { refusal }.
853
+ async function resolveInitAddons({ isInteractive, isStaticSite, withList, capabilities, initOptions, targetDir, region }) {
854
+ const failAddonResolution = (cap, resolved) => {
855
+ if (!resolved.ok && resolved.cancelled) {
856
+ return failCommand({
857
+ print: () => cancel('Selection cancelled.'),
858
+ event: 'cli-error',
859
+ telemetry: { step: 'init_addons', reason: 'cancelled' },
860
+ reason: 'cancelled',
861
+ exitCode: null,
862
+ });
863
+ }
864
+ return failCommand({
865
+ message: resolved.message,
866
+ hint: resolved.hint ?? null,
867
+ event: 'cli-error',
868
+ telemetry: { step: 'init_addons', error_code: resolved.errorCode },
869
+ reason: resolved.reason,
870
+ resultExtra: { capability: cap },
871
+ });
872
+ };
721
873
 
722
874
  // Addon selection: interactive multiselect, or explicit --with.
723
875
  let selectedAddons;
@@ -766,9 +918,9 @@ async function mainStackMain(input = {}) {
766
918
  });
767
919
  if (typeof useDefault === 'symbol') process.exit(0);
768
920
  const resolved = await resolveAddonOptions(cap, {}, {
769
- cwd: dirConfig.targetDir, region: config.region, isInteractive: !useDefault,
921
+ cwd: targetDir, region, isInteractive: !useDefault,
770
922
  });
771
- if (!resolved.ok) return failAddonResolution(cap, resolved);
923
+ if (!resolved.ok) return { refusal: await failAddonResolution(cap, resolved) };
772
924
  resolvedByCap[cap] = resolved;
773
925
  continue;
774
926
  }
@@ -778,521 +930,558 @@ async function mainStackMain(input = {}) {
778
930
  ? { domain: initOptions.domain ?? undefined, zoneId: initOptions.zoneId ?? undefined, fromEmail: initOptions.fromEmail ?? undefined }
779
931
  : {};
780
932
  const resolved = await resolveAddonOptions(cap, opts, {
781
- cwd: dirConfig.targetDir,
782
- region: config.region,
933
+ cwd: targetDir,
934
+ region,
783
935
  isInteractive: isInteractive && cap === 'email:ses',
784
936
  });
785
- if (!resolved.ok) return failAddonResolution(cap, resolved);
937
+ if (!resolved.ok) return { refusal: await failAddonResolution(cap, resolved) };
786
938
  resolvedByCap[cap] = resolved;
787
939
  }
940
+ return { selectedAddons, resolvedByCap };
941
+ }
788
942
 
789
- // 3.5 Docker Compose Overrides. The web service is the `build:`
790
- // service first, then the framework-port match, then the first
791
- // non-datastore service — never an anointed database. A
792
- // datastore-only file skips the merge (and the port override) with a
793
- // loud warning in both modes; the selection passes through to the
794
- // generator so it merges without re-warning.
795
- let composeForMerge = dockerCompose;
796
- let composeWebName = null;
797
- if (dockerCompose && dockerCompose.length > 0) {
798
- const selection = selectComposeWebService(dockerCompose, {
799
- frameworkPort: frameworkDefaultPort(config.framework),
943
+ // Step 3b (CI opt-ins). Drift detection and plan-on-PR: explicit flag
944
+ // wins, else offer interactively.
945
+ async function resolveCiOptIns({ initOptions, isInteractive }) {
946
+ // Scheduled IaC drift detection: explicit flag wins, else offer.
947
+ // Opt-in by default — the workflow opens GitHub Issues on its own.
948
+ const setupCiDriftFlag = initOptions.setupCiDrift === true;
949
+ let driftEnabled = false;
950
+ if (setupCiDriftFlag) {
951
+ driftEnabled = true;
952
+ } else if (isInteractive) {
953
+ const driftAnswer = await confirm({
954
+ message: 'Set up scheduled IaC drift detection (daily terraform plan + GitHub Issues)?',
955
+ initialValue: false,
800
956
  });
801
- if (!selection.service) {
802
- console.log(color.yellow('⚠️ No app service detected in your compose file (every service looks like a datastore) — skipping the compose merge. Give your app service a `build:` key and re-run to merge it.'));
803
- trackEvent('compose_merge_skipped', { projectName: dirConfig.actualProjectName, reason: selection.skipped });
804
- composeForMerge = null;
805
- } else {
806
- composeWebName = selection.service.name;
807
- if (selection.datastoreImage) {
808
- console.log(color.yellow(`⚠️ Compose service "${selection.service.name}" looks like a datastore but was selected as the web service — verify the merged port and env vars before applying.`));
809
- trackEvent('compose_datastore_web_warned', { projectName: dirConfig.actualProjectName, service: selection.service.name });
810
- }
811
- if (selection.service.port) {
812
- // Override the config port with the one from Docker Compose
813
- config.port = selection.service.port.toString();
814
- if (!isHeadless) {
815
- console.log(color.cyan(` 🐳 Docker Compose overrides: Port set to ${config.port} via service "${selection.service.name}"`));
816
- }
817
- }
818
- }
957
+ if (typeof driftAnswer === 'symbol') process.exit(0);
958
+ driftEnabled = driftAnswer === true;
819
959
  }
820
960
 
821
- // 4. Framework Migration Checks (Vercel Escape Hatch)
822
- if ((target === 'lambda' || target === 'static') && vercelRules?.redirects?.length > 0) {
823
- const remedy = target === 'static'
824
- ? 'Recreate them as CloudFront Functions after provisioning.'
825
- : 'Recreate them as API Gateway routes after provisioning.';
826
- log.warn(color.yellow(`⚠️ vercel.json redirects were detected, but ${target === 'static' ? 'static' : 'Lambda'} targets have no ALB listener rules to translate them into. ${remedy}`));
961
+ // Plan-on-PR: explicit flag wins, else offer. Defaults ON —
962
+ // reviewing infra changes before merge is the safe default.
963
+ const setupCiPlanFlag = initOptions.setupCiPlan === true;
964
+ let planEnabled = false;
965
+ if (setupCiPlanFlag) {
966
+ planEnabled = true;
967
+ } else if (isInteractive) {
968
+ const planAnswer = await confirm({
969
+ message: 'Post Terraform plans as PR comments (review infra changes before merge)?',
970
+ initialValue: true,
971
+ });
972
+ if (typeof planAnswer === 'symbol') process.exit(0);
973
+ planEnabled = planAnswer === true;
827
974
  }
975
+ return { driftEnabled, planEnabled };
976
+ }
828
977
 
829
- // Headers/rewrites have no translator on any target — name the dropped
830
- // counts loudly, or the "Migrating edge network rules" success line
831
- // reads as if everything migrated.
832
- {
833
- const migratedRedirects = (target === 'lambda' || target === 'static') ? 0 : (vercelRules?.redirects?.length || 0);
834
- const droppedHeaders = vercelRules?.headers?.length || 0;
835
- const droppedRewrites = vercelRules?.rewrites?.length || 0;
836
- if (droppedHeaders > 0 || droppedRewrites > 0) {
837
- const dropped = [
838
- droppedHeaders > 0 ? `${droppedHeaders} header rule${droppedHeaders === 1 ? '' : 's'}` : null,
839
- droppedRewrites > 0 ? `${droppedRewrites} rewrite${droppedRewrites === 1 ? '' : 's'}` : null,
840
- ].filter(Boolean).join(' and ');
841
- log.warn(color.yellow(`⚠️ vercel.json ${dropped} were detected but are not migrated (only redirects translate to ALB listener rules — ${migratedRedirects} migrated). Recreate them as CloudFront Functions or ALB listener rules after provisioning.`));
978
+ // Step 3b (migration gate). Pre-deploy migration command + gate toggle
979
+ // plus the stripped-runner guard. Returns the command, its source, and
980
+ // the toggle — or { refusal }.
981
+ async function resolveMigrationGate({ initOptions, capabilities, target, needsDatabase, framework, isInteractive, targetDir, projectName }) {
982
+ // Pre-deploy migration gate: explicit flag wins, else prompt. An
983
+ // explicit --setup-ci-migrate=<cmd> overrides detection, which is the
984
+ // escape hatch when detection yields an npm shim on a stripped runner.
985
+ const setupCiMigrateOpt = initOptions.setupCiMigrate;
986
+ const explicitMigrationCmd = typeof setupCiMigrateOpt === 'string' && setupCiMigrateOpt.trim() !== ''
987
+ ? setupCiMigrateOpt.trim()
988
+ : null;
989
+ const setupCiMigrateFlag = setupCiMigrateOpt === true || typeof setupCiMigrateOpt === 'string';
990
+ const migrationCmd = explicitMigrationCmd || capabilities.migration.command;
991
+ const migrationCmdSource = explicitMigrationCmd ? 'explicit' : 'detected';
992
+ let migrationGateEnabled = false;
993
+ if ((target === 'lambda' || target === 'static') && (setupCiMigrateFlag || (needsDatabase && migrationCmd))) {
994
+ log.warn(color.yellow(`⚠️ Skipping the pre-deploy migration gate: it runs migrations as an ephemeral ECS task, which ${target === 'static' ? 'static' : 'Lambda'} targets don't provision. Run migrations from CI against your database endpoint instead.`));
995
+ } else if (needsDatabase && migrationCmd) {
996
+ if (setupCiMigrateFlag) {
997
+ migrationGateEnabled = true;
998
+ } else if (isInteractive) {
999
+ const gateAnswer = await confirm({
1000
+ message: `Enable pre-deploy database migration gate in GitHub Actions? (${migrationCmdSource}: ${migrationCmd})`,
1001
+ initialValue: true,
1002
+ });
1003
+ if (typeof gateAnswer === 'symbol') process.exit(0);
1004
+ migrationGateEnabled = gateAnswer === true;
842
1005
  }
1006
+ } else if (setupCiMigrateFlag) {
1007
+ log.warn(color.yellow('⚠️ --setup-ci-migrate was passed but no database is configured or no migration command was given; skipping the migration gate.'));
843
1008
  }
844
1009
 
845
- if (config.framework === 'nestjs') {
846
- const nestAnalysis = analyzeNestApp(dirConfig.targetDir);
847
- if (nestAnalysis.hasMain && !nestAnalysis.listensOnAllInterfaces) {
848
- log.warn(color.yellow(`⚠️ NestJS must listen on 0.0.0.0 to receive traffic in ${target === 'lambda' ? 'AWS Lambda' : 'AWS Fargate'}.`));
849
- console.log(color.cyan(` In ${nestAnalysis.filePath}, update your bootstrap:`));
850
- console.log(color.green(` await app.listen(process.env.PORT ?? 3000, '0.0.0.0');\n`));
851
- }
852
- } else if (config.framework === 'nextjs') {
853
- const nextConfig = analyzeNextConfig(dirConfig.targetDir);
854
- // Static exports need no container, so the standalone warning
855
- // (container-image slimming) does not apply to them.
856
- if (nextConfig.hasConfig && !nextConfig.isStandalone && !nextConfig.isExport) {
857
- log.warn(color.yellow('⚠️ Next.js config is missing "output: \'standalone\'".'));
858
- console.log(color.cyan(' Fix it here: https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/migrations/nextjs-vercel-to-aws.md'));
859
- }
860
- } else if (detectedFramework?.id === 'svelte') {
861
- const svelteConfig = analyzeSvelteConfig(dirConfig.targetDir);
862
- if (svelteConfig.adapter === 'vercel' || svelteConfig.adapter === 'auto') {
863
- log.warn(color.yellow('⚠️ SvelteKit is locked into the Vercel/Auto adapter.'));
864
- console.log(color.cyan(' Fix it here: https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/migrations/sveltekit-vercel-to-aws.md'));
1010
+ // Stripped-runner guard: init is about to generate a node
1011
+ // Dockerfile without npm/npx, so wiring an npm-shim command into the
1012
+ // gate would fail 100% of deploys. Fail fast headless (re-run with an
1013
+ // explicit node command); warn loudly interactively and continue.
1014
+ if (migrationGateEnabled && isNpmShimCommand(migrationCmd) && target === 'ecs' && frameworkUsesStrippedRunner(framework)) {
1015
+ const ormHint = ormMappedHintSegment(targetDir, '--setup-ci-migrate=');
1016
+ if (!isInteractive) {
1017
+ return {
1018
+ refusal: await failCommand({
1019
+ message: `\n✖ Refusing to wire the pre-deploy migration gate with "${migrationCmd}": the generated ${framework} Dockerfile strips npm/npx from the runner image, so this command would fail with "command not found" on every deploy.\n`,
1020
+ hint: ` Re-run with an explicit node-based command, e.g. \`--setup-ci-migrate="node ./dist/migrate.cjs"\`, or wire the gate later with \`grada db migrate --cmd "node ./dist/migrate.cjs" --setup-ci\`. Ensure your Dockerfile builds the bundle and copies it into the runner image${ormHint}.\n`,
1021
+ event: 'cli-error',
1022
+ telemetry: { step: 'init_setup', cmd_source: migrationCmdSource, error_code: 'NPM_CMD_STRIPPED_RUNNER' },
1023
+ errorCode: 'NPM_CMD_STRIPPED_RUNNER',
1024
+ reason: 'npm-cmd-stripped-runner',
1025
+ }),
1026
+ };
865
1027
  }
866
- } else if (detectedFramework?.name === 'Astro') {
867
- const astroConfig = analyzeAstroConfig(dirConfig.targetDir);
868
- if (astroConfig.adapter === 'vercel') {
869
- log.warn(color.yellow('⚠️ Astro is locked into the Vercel adapter.'));
870
- console.log(color.cyan(' Fix it here: https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/migrations/astro-vercel-to-aws.md'));
1028
+ console.log(color.yellow(`⚠️ The ${migrationCmdSource} migration command ("${migrationCmd}") starts with npm/npx but the generated ${framework} Dockerfile strips those binaries from the runner image — the gate will fail unless you switch to a node-based command (e.g. "node ./dist/migrate.cjs"). Ensure your Dockerfile builds the bundle and copies it into the runner image.${ormHint}`));
1029
+ trackEvent('npm_cmd_stripped_runner', { projectName, cmd_source: migrationCmdSource, ci_setup: true });
1030
+ }
1031
+ return { migrationCmd, migrationCmdSource, migrationGateEnabled };
1032
+ }
1033
+
1034
+ // Step 3b (worker). Background worker command: Procfile-driven as before,
1035
+ // plus detection-driven. Lambda targets have no ECS worker service, so the
1036
+ // prompt is skipped and any Procfile worker process is left out of the
1037
+ // generated stack.
1038
+ async function resolveWorkerCommand({ isInteractive, isStaticSite, target, procfile, capabilities, needsDatabase }) {
1039
+ let workerCommandHcl = '';
1040
+ if (isInteractive && !isStaticSite && target !== 'lambda' && target !== 'static' && (procfile?.worker || capabilities.worker.detected)) {
1041
+ const workerAnswer = await promptWorkerCommand(procfile, capabilities);
1042
+ if (workerAnswer.trim() !== '') {
1043
+ workerCommandHcl = `command = ${toHclStringArray(splitProcfileCommand(workerAnswer.trim()))}`;
871
1044
  }
872
1045
  }
1046
+ if (!isInteractive && !isStaticSite && target !== 'lambda' && target !== 'static' && !procfile?.worker && capabilities.worker.detected) {
1047
+ // The suggested command is an npm shim (broken on stripped
1048
+ // runners), so headless never scaffolds it blindly — but the
1049
+ // detection must not vanish silently either.
1050
+ const evidence = (capabilities.worker.evidence || []).join(', ') || 'worker signals';
1051
+ const suggested = capabilities.worker.suggestedCommand || 'none';
1052
+ log.warn(color.yellow(`⚠️ Skipping the background worker: detection found ${evidence} but no Procfile worker process, and the suggested command ("${suggested}") needs interactive confirmation. Re-run init interactively to configure the worker command.`));
1053
+ }
1054
+ if (target === 'lambda' && (procfile?.worker || capabilities.worker.detected)) {
1055
+ log.warn(color.yellow('⚠️ Skipping the background worker: Lambda targets run a single scale-to-zero function with no ECS worker service.'));
1056
+ }
1057
+ if (target === 'lambda' && needsDatabase) {
1058
+ log.warn(color.yellow('⚠️ Lambda opens a database connection per concurrent execution with no proxy in between — bursts can exhaust RDS limits. Keep pools tiny (tradeoffs: https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/architecture.md#fargate-vs-lambda-tradeoffs).'));
1059
+ }
1060
+ const willHaveWorker = target !== 'lambda' && target !== 'static' && (Boolean(procfile?.worker) || workerCommandHcl !== '');
1061
+ return { workerCommandHcl, willHaveWorker };
1062
+ }
873
1063
 
874
- // 5. Calculate Derived Values
875
- const cpu = config.size === 'small' ? '512' : '256';
876
- const memory = config.size === 'small' ? '1024' : '512';
877
- const computeTier = config.size === 'small' ? 'Small (0.5 vCPU, 1GB RAM)' : 'Micro (0.25 vCPU, 512MB RAM)';
1064
+ // Step 3b (static limits). Static targets serve files with no compute:
1065
+ // refuse mismatched frameworks, skip worker + database with warnings.
1066
+ // Mutates config.needsDatabase. Returns { isStaticSite } or { refusal }.
1067
+ async function applyStaticCompositionLimits({ target, config, detectedFramework, procfile, capabilities }) {
1068
+ const isStaticSite = config.framework === 'static';
1069
+ // Static exports (Next.js output:'export', SvelteKit adapter-static)
1070
+ // carry no server, so --target static admits them like static presets.
1071
+ // This extends only the gate — prompts.js still resolves the container
1072
+ // preset from the detected id on ecs/lambda.
1073
+ const isStaticExport = detectedFramework?.isStaticExport === true;
1074
+ if (target === 'static' && !isStaticSite && !isStaticExport) {
1075
+ return {
1076
+ refusal: await failCommand({
1077
+ message: `\n✖ --target static only supports static-site frameworks (detected: ${config.framework}).\n`,
1078
+ hint: ' Use --target ecs for containerized apps or --target lambda for scale-to-zero serverless.\n',
1079
+ event: 'cli-error',
1080
+ telemetry: { step: 'init_validation', error_code: 'STATIC_TARGET_FRAMEWORK_MISMATCH' },
1081
+ reason: 'static-target-framework-mismatch',
1082
+ resultExtra: { framework: config.framework },
1083
+ }),
1084
+ };
1085
+ }
1086
+ if (target === 'static' && (procfile?.worker || capabilities.worker.detected)) {
1087
+ log.warn(color.yellow('⚠️ Skipping the background worker: static targets serve files from S3 + CloudFront with no compute to run it on.'));
1088
+ }
1089
+ if (target === 'static' && config.needsDatabase) {
1090
+ log.warn(color.yellow('⚠️ Skipping the database: static targets have no compute to connect from. Provision data separately if the site needs an API.'));
1091
+ config.needsDatabase = false;
1092
+ }
1093
+ return { isStaticSite };
1094
+ }
878
1095
 
879
- const costs = estimateMonthlyCost({
880
- cpu: parseInt(cpu),
881
- memory: parseInt(memory),
882
- hasDb: config.needsDatabase,
883
- dbEngine: config.dbEngine,
884
- hasWorker: willHaveWorker,
885
- hasSecrets: target !== 'static',
886
- addons: selectedAddons,
887
- computeTarget: target,
1096
+ // Step 3. Gather Configuration & Framework Quirks: project config,
1097
+ // OIDC trust scoping, db-engine defaulting, and framework quirks.
1098
+ // Returns the config bundle, or { refusal }.
1099
+ async function gatherInitConfig({ isHeadless, headlessOptions, targetDir, detectedFramework, capabilities, explicitDbEngine, target, explicitGitHubRepo, projectName, procfile, force, isInteractive }) {
1100
+ const config = await getProjectConfig(isHeadless, headlessOptions, targetDir, detectedFramework, { capabilities, dbEngine: explicitDbEngine, target });
1101
+ config.target = target;
1102
+
1103
+ // 3a. Scope the GitHub OIDC trust (see resolveOidcTrust): explicit flag
1104
+ // wins, then the tree's rendered trust, then the git remote, then one
1105
+ // skippable prompt; headless falls through to the open trust — unless
1106
+ // that would widen a non-trivial existing claim, which refuses
1107
+ // (headless) or confirms (interactive). Telemetry records the mode
1108
+ // only — never the owner/repo.
1109
+ const oidcResolution = await resolveOidcTrust({
1110
+ explicitSlug: explicitGitHubRepo,
1111
+ treeClaim: readTerraformOidcTrust(targetDir),
1112
+ targetDir,
1113
+ isInteractive,
888
1114
  });
889
- const estimatedCost = costs.totalMonthly;
890
- const buildDir = detectedFramework?.buildDir || 'dist';
1115
+ if (oidcResolution.refusal) {
1116
+ return { refusal: await failCommand({ ...oidcResolution.refusal }) };
1117
+ }
1118
+ if (oidcResolution.cancelled) {
1119
+ cancel('Operation cancelled. Re-run with --github-repo owner/name to scope the trust explicitly.');
1120
+ process.exit(0);
1121
+ }
1122
+ const { sub: oidcTrustSub, source: oidcTrustSource } = oidcResolution;
1123
+ trackEvent('init_oidc_trust', {
1124
+ projectName,
1125
+ mode: oidcTrustSub === 'repo:*' ? 'fallback' : 'scoped',
1126
+ source: oidcTrustSource,
1127
+ });
1128
+ // Explicit flag wins everywhere (headless defaults to postgres, the
1129
+ // interactive prompt is skipped); anything else falls back to postgres.
1130
+ if (explicitDbEngine) {
1131
+ config.dbEngine = explicitDbEngine;
1132
+ } else if (!VALID_DB_ENGINES.includes(config.dbEngine)) {
1133
+ config.dbEngine = 'postgres';
1134
+ }
1135
+ const djangoWsgi = await resolveDjangoWsgi(targetDir, procfile, config.framework, isHeadless);
1136
+ const disableDefaultCI = await handleRailsCI(targetDir, config.framework, isHeadless, { force });
1137
+ return { config, oidcResolution, oidcTrustSub, djangoWsgi, disableDefaultCI };
1138
+ }
891
1139
 
892
- // 6. Plan existing-file handling BEFORE provisioning: headless fail
893
- // paths fire here while the tree is still intact, and the actual
894
- // renames wait until provisioning succeeds.
895
- const existingFilesPlan = await planExistingFiles(dirConfig.targetDir, { isHeadless, force: initOptions.force });
896
- const existingFilesRefusal = await refusalResultForPlan(existingFilesPlan);
897
- if (existingFilesRefusal) return existingFilesRefusal;
898
- // Stash preserved files before anything mutates the tree; the stash is
899
- // discarded untouched when provisioning fails below.
900
- const preservedStash = preserveManagedFiles(dirConfig.targetDir);
1140
+ // Step 2d. Codebase scans: framework, Procfile, vercel.json,
1141
+ // docker-compose, and capability detection, plus the detection log lines.
1142
+ function scanInitCodebase({ targetDir, isHeadless }) {
1143
+ const detectedFramework = detectFramework(targetDir);
1144
+ const procfile = parseProcfile(targetDir);
1145
+ const vercelRules = parseVercelConfig(targetDir);
1146
+ const dockerCompose = parseDockerCompose(targetDir);
1147
+ const capabilities = detectProjectCapabilities(targetDir);
901
1148
 
902
- const s = spinner();
903
- s.start('Provisioning infrastructure...');
1149
+ if (!isHeadless) {
1150
+ if (detectedFramework) log.success(`Auto-detected framework: ${detectedFramework.name}`);
1151
+ if (procfile && procfile.web) log.success(`Auto-detected Procfile (web command: ${procfile.web.join(' ')})`);
1152
+ if (vercelRules) log.success(`Auto-detected vercel.json (Migrating edge network rules)`);
1153
+ if (dockerCompose) log.success(`Auto-detected docker-compose.yml (${dockerCompose.length} services mapped)`);
1154
+ }
1155
+
1156
+ if (isHeadless) console.log(color.cyan(`🤖 Running grada in headless mode`));
1157
+ return { detectedFramework, procfile, vercelRules, dockerCompose, capabilities };
1158
+ }
1159
+
1160
+ // Step 2c. Compute target (explicit flag wins, headless defaults to ECS,
1161
+ // interactive runs prompt) plus the capability-vs-target policy for
1162
+ // --with. Returns { target } or { refusal }.
1163
+ async function resolveInitTarget({ isInteractive, normalizedExplicitTarget, withList }) {
1164
+ let target = normalizedExplicitTarget || 'ecs';
1165
+ if (isInteractive && normalizedExplicitTarget === null) {
1166
+ log.info(`${color.gray('📖 Compare tradeoffs (cost crossover, cold starts, DB connections):')} ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/architecture.md')}`);
1167
+ const targetAnswer = await select({
1168
+ message: 'Select your AWS compute target:',
1169
+ options: [
1170
+ { value: 'ecs', label: 'ECS Fargate + ALB', hint: 'Always-on, persistent DB connections, zero cold starts (Starts at ~$31/mo)' },
1171
+ { value: 'lambda', label: 'AWS Lambda + API Gateway v2', hint: 'Scale-to-zero, usage-based compute, 3-5s VPC cold starts ($0/mo idle)' },
1172
+ { value: 'static', label: 'Static site (S3 + CloudFront)', hint: 'Zero-compute hosting for SPAs/SSGs ($0/mo idle)' },
1173
+ ],
1174
+ });
1175
+ if (typeof targetAnswer === 'symbol') process.exit(0);
1176
+ target = targetAnswer;
1177
+ }
904
1178
 
905
- let awsAccountId, stateBucketName;
906
- let adoptionRefusal = null;
907
- const offlineScaffold = initOptions.offline === true;
908
- try {
909
- if (offlineScaffold) {
910
- // Scaffold-only mode for template development and CI
911
- // fixtures — no AWS calls. Placeholders are greppable and
912
- // invalid as real values (uppercase), so an unreconciled tree
913
- // fails loud at `terraform init` instead of half-working.
914
- awsAccountId = OFFLINE_ACCOUNT_PLACEHOLDER;
915
- stateBucketName = formatStateBucketName(`${dirConfig.actualProjectName}${resourceSuffix}`, OFFLINE_ACCOUNT_PLACEHOLDER);
916
- s.stop('Offline mode: skipping state bucket provisioning.');
917
- trackEvent('init_offline_scaffold', { projectName: dirConfig.actualProjectName });
918
- } else {
919
- const bucketData = await provisionStateBucket(config.region, `${dirConfig.actualProjectName}${resourceSuffix}`);
920
- awsAccountId = bucketData.awsAccountId;
921
- stateBucketName = bucketData.stateBucketName;
922
- // Adoption gate: a fresh tree pointing at a bucket that already
923
- // holds state needs an explicit adopt/rename/wipe choice before
924
- // anything touches the tree. Probe failures fail closed through
925
- // the provisioning catch below.
926
- const isFreshTree = existingFilesPlan.decision === 'clean' && existingFilesPlan.foundFiles.length === 0;
927
- // An interactive prompt may fire below: park the spinner first
928
- // so it doesn't scribble over the choice (precedent: apply's
929
- // recovery prompt). Headless runs never prompt.
930
- const mayPromptAdoption = !isHeadless && initOptions.adoptState !== true && isFreshTree;
931
- if (mayPromptAdoption) s.stop('State bucket ready.');
932
- adoptionRefusal = await checkStateAdoption({
933
- s3: bucketData.s3Client ?? null,
934
- bucket: stateBucketName,
935
- isFreshTree,
936
- isHeadless,
937
- adoptState: initOptions.adoptState === true,
1179
+ // Capability-vs-target policy for --with: refuse fast when
1180
+ // the requested capability cannot render on this target (static has
1181
+ // no task role or VPC), before any prompt/AWS call/write. Interactive
1182
+ // multiselect offers only compatible targets' caps; this covers --with.
1183
+ for (const cap of withList) {
1184
+ if (!ADDON_REGISTRY[cap]) continue;
1185
+ if (addonTargetDisposition(cap, target) === 'refuse') {
1186
+ const targetGuard = guardComputeTarget({
1187
+ actual: target,
1188
+ command: `init --with ${cap}`,
1189
+ supported: addonSupportedTargets(cap),
1190
+ hint: 'Static sites run no containers — this capability needs a compute target (--target ecs or lambda).',
938
1191
  });
939
- if (mayPromptAdoption && !adoptionRefusal) s.start('Provisioning infrastructure...');
1192
+ return {
1193
+ refusal: await failCommand({
1194
+ message: targetGuard.message,
1195
+ hint: targetGuard.hint,
1196
+ event: 'cli-error',
1197
+ telemetry: { step: 'init_validation', error_code: targetGuard.errorCode },
1198
+ reason: targetGuard.reason,
1199
+ resultExtra: { capability: cap },
1200
+ }),
1201
+ };
940
1202
  }
941
- } catch (error) {
942
- s.stop('❌ Failed to provision remote state or authenticate with AWS.');
943
- trackEvent('init_backup_deferred', {
944
- projectName: dirConfig.actualProjectName,
945
- plan: existingFilesPlan.decision,
1203
+ }
1204
+ return { target };
1205
+ }
1206
+
1207
+ // Step 2b. Fail-fast validation of init composition flags — before any
1208
+ // prompts, AWS calls, backups, or file writes. Returns the parsed flag
1209
+ // values, or { refusal }.
1210
+ async function validateInitFlags({ initOptions, headlessOptions, isInteractive, explicitGitHubRepo, targetDir }) {
1211
+ const refuse = async (args) => ({ refusal: await failCommand(args) });
1212
+ const explicitFramework = typeof headlessOptions.framework === 'string' && headlessOptions.framework.trim() !== ''
1213
+ ? headlessOptions.framework.trim()
1214
+ : null;
1215
+ if (explicitFramework !== null && !SUPPORTED_FRAMEWORKS.includes(explicitFramework)) {
1216
+ return refuse({
1217
+ message: `\n✖ Unknown framework "${explicitFramework}".`,
1218
+ hint: ` Supported frameworks: ${SUPPORTED_FRAMEWORKS.join(', ')}.\n${explicitFramework === 'express' ? ' Express apps use --framework=node.\n' : ''}`,
1219
+ event: 'cli-error',
1220
+ telemetry: { step: 'init_validation', error_code: 'INVALID_FRAMEWORK' },
1221
+ reason: 'invalid-framework',
946
1222
  });
947
- // Auth failures print the shared credential-recovery guidance;
948
- // init keeps its own telemetry + exit path through failCommand.
949
- if (isAuthError(error)) printAwsAuthGuidance(initOptions);
950
- return failCommand({
951
- message: `AWS Error: ${error.message}`,
952
- useErrorStream: true,
1223
+ }
1224
+ if (explicitGitHubRepo !== null && !isValidGitHubRepoSlug(explicitGitHubRepo)) {
1225
+ return refuse({
1226
+ message: `\n✖ Invalid --github-repo "${explicitGitHubRepo}".`,
1227
+ hint: ' Expected owner/name (e.g. --github-repo=acme/widgets).\n',
953
1228
  event: 'cli-error',
954
- telemetry: { step: 'aws_provisioning', error_code: error.name || 'UNKNOWN', error_message: error.message },
1229
+ telemetry: { step: 'init_validation', error_code: 'INVALID_GITHUB_REPO' },
1230
+ reason: 'invalid-github-repo',
955
1231
  });
956
1232
  }
957
- if (adoptionRefusal) return failCommand(adoptionRefusal);
958
-
959
- // Provisioning succeeded: move the old tree aside (no-op on a clean
960
- // slate), then regenerate over the cleared ground.
961
- await executeBackup(dirConfig.targetDir, existingFilesPlan);
962
-
963
- // 7. Synthesize Templates
964
- s.message('Synthesizing Terraform templates...');
965
- // Live origin/HEAD wins when it names a real branch; when
966
- // detection falls back, a re-init keeps the tree's own default branch
967
- // so dual trust never narrows silently.
968
- const treeDefaultBranch = oidcResolution.treeBranches?.[1] ?? null;
969
- const detectedDefaultBranch = resolveDefaultBranch(dirConfig.targetDir, config.branch);
970
- const defaultBranch = detectedDefaultBranch !== config.branch
971
- ? detectedDefaultBranch
972
- : (treeDefaultBranch ?? config.branch);
973
- if (defaultBranch !== config.branch && treeDefaultBranch === null) {
974
- log(color.yellow(`⚠️ Trusting default branch "${defaultBranch}" alongside deploy branch "${config.branch}" so scheduled drift can assume the deploy role.`));
1233
+ const withList = Array.isArray(initOptions.with)
1234
+ ? initOptions.with.filter((cap) => typeof cap === 'string')
1235
+ : [];
1236
+ const unknownCaps = withList.filter((cap) => !ADDON_REGISTRY[cap]);
1237
+ if (unknownCaps.length > 0) {
1238
+ return refuse({
1239
+ message: `\n✖ Unknown addon capabilities: ${unknownCaps.join(', ')}.`,
1240
+ hint: ` Valid capabilities: ${Object.keys(ADDON_REGISTRY).join(', ')}.\n`,
1241
+ event: 'cli-error',
1242
+ telemetry: { step: 'init_validation', error_code: 'UNSUPPORTED_CAPABILITY' },
1243
+ reason: 'unsupported-capability',
1244
+ resultExtra: { capabilities: withList },
1245
+ });
975
1246
  }
976
- const { deploySub, previewSub } = renderOidcRoleSubs(oidcTrustSub, config.branch, defaultBranch);
977
- const renderConfig = {
978
- PROJECT_NAME: dirConfig.actualProjectName,
979
- RESOURCE_SUFFIX: resourceSuffix,
980
- REGION: config.region,
981
- PORT: config.port,
982
- CPU: cpu,
983
- MEMORY: memory,
984
- COMPUTE_TIER: computeTier,
985
- ESTIMATED_COST: estimatedCost,
986
- STATE_BUCKET: stateBucketName,
987
- AWS_ACCOUNT_ID: awsAccountId,
988
- HEALTH_CHECK_PATH: config.healthCheckPath,
989
- DESIRED_COUNT: config.desiredCount,
990
- DEPLOY_BRANCH: config.branch,
991
- DEPLOY_ROLE_NAME: buildDeployRoleName(dirConfig.actualProjectName, resourceSuffix),
992
- PREVIEW_ROLE_NAME: buildPreviewRoleName(dirConfig.actualProjectName, resourceSuffix),
993
- GITHUB_DEPLOY_SUB: deploySub,
994
- GITHUB_PREVIEW_SUB: previewSub,
995
- BUILD_DIR: buildDir,
996
- finalFramework: config.framework,
997
- NEEDS_DATABASE: config.needsDatabase,
998
- DB_ENGINE: config.dbEngine,
999
- DJANGO_WSGI: djangoWsgi,
1000
- DISABLE_DEFAULT_CI: disableDefaultCI,
1001
- PROCFILE: procfile,
1002
- VERCEL_RULES: vercelRules,
1003
- DOCKER_COMPOSE: composeForMerge,
1004
- DOCKER_COMPOSE_WEB: composeWebName,
1005
- ENABLE_PR_PREVIEWS: config.enablePrPreviews,
1006
- WORKER_COMMAND: workerCommandHcl,
1007
- TARGET: target
1008
- };
1009
- await generateTemplates(dirConfig.targetDir, renderConfig);
1010
- if (Array.isArray(renderConfig.COMPOSE_SECRETS_FILTERED) && renderConfig.COMPOSE_SECRETS_FILTERED.length > 0) {
1011
- trackEvent('compose_secrets_filtered', {
1012
- projectName: dirConfig.actualProjectName,
1013
- count: renderConfig.COMPOSE_SECRETS_FILTERED.length,
1014
- names: renderConfig.COMPOSE_SECRETS_FILTERED,
1247
+ const explicitDbEngine = typeof initOptions.dbEngine === 'string' && initOptions.dbEngine.trim() !== ''
1248
+ ? initOptions.dbEngine.trim()
1249
+ : null;
1250
+ if (explicitDbEngine !== null && !VALID_DB_ENGINES.includes(explicitDbEngine)) {
1251
+ return refuse({
1252
+ message: `\n✖ Invalid --db-engine "${explicitDbEngine}".`,
1253
+ hint: ` Valid engines: ${VALID_DB_ENGINES.join(', ')}.\n`,
1254
+ event: 'cli-error',
1255
+ telemetry: { step: 'init_validation', error_code: 'INVALID_DB_ENGINE' },
1256
+ reason: 'invalid-db-engine',
1015
1257
  });
1016
1258
  }
1017
-
1018
- // 7b. Scaffold selected addons (registry order), then wire the
1019
- // pre-deploy migration gate into the generated workflow.
1020
- for (const cap of selectedAddons) {
1021
- const scaffolded = await scaffoldAddon(cap, resolvedByCap[cap], { cwd: dirConfig.targetDir, region: config.region });
1022
- console.log(color.green(`✅ Scaffolded terraform/${scaffolded.file} (${cap})`));
1259
+ const explicitTarget = typeof initOptions.target === 'string' && initOptions.target.trim() !== ''
1260
+ ? initOptions.target.trim()
1261
+ : null;
1262
+ const normalizedExplicitTarget = explicitTarget === 'fargate' ? 'ecs' : explicitTarget;
1263
+ if (explicitTarget !== null && !COMPUTE_TARGETS.includes(normalizedExplicitTarget)) {
1264
+ return refuse({
1265
+ message: `\n✖ Invalid compute target "${explicitTarget}". Supported targets: ecs, lambda, static.`,
1266
+ hint: ' Use --target ecs (or fargate) for always-on containers, --target lambda for scale-to-zero serverless, or --target static for zero-compute S3 + CloudFront hosting.\n',
1267
+ event: 'cli-error',
1268
+ telemetry: { step: 'init_validation', error_code: 'INVALID_COMPUTE_TARGET' },
1269
+ reason: 'invalid-compute-target',
1270
+ });
1023
1271
  }
1024
-
1025
- if (migrationGateEnabled && migrationCmd) {
1026
- const deployYmlPath = path.join(dirConfig.targetDir, '.github', 'workflows', 'deploy.yml');
1027
- const workflowContent = readFileSafe(deployYmlPath);
1028
- // Scope the gate's snapshot id to the database (aurora
1029
- // takes the cluster prefix) so guardrails and gc can name it.
1030
- const gateDbRefs = resolveDbEngineRefs(config.dbEngine);
1031
- const gateDbIdentifier = `${dirConfig.actualProjectName}${resourceSuffix}-db${gateDbRefs.isCluster ? '-cluster' : ''}`;
1032
- const gated = workflowContent ? injectMigrationGate(workflowContent, { cmd: migrationCmd, cliVersion: CLI_VERSION, dbIdentifier: gateDbIdentifier }) : null;
1033
- if (gated) {
1034
- atomicWriteFileSync(deployYmlPath, gated);
1035
- console.log(color.green('✅ Wired the pre-deploy database migration gate into .github/workflows/deploy.yml (snapshot first, then migrate)'));
1036
- } else {
1037
- log.warn(color.yellow('⚠️ Could not wire the migration gate: the deploy workflow anchor was not found.'));
1272
+ const addonFlagOptions = {
1273
+ model: initOptions.model ?? undefined,
1274
+ domain: initOptions.domain ?? undefined,
1275
+ zoneId: initOptions.zoneId ?? undefined,
1276
+ fromEmail: initOptions.fromEmail ?? undefined,
1277
+ };
1278
+ for (const cap of withList) {
1279
+ // Per-capability scoped: irrelevant flags are silently ignored.
1280
+ const flagError = validateAddonFlags(cap, addonFlagOptions);
1281
+ if (flagError) {
1282
+ return refuse({
1283
+ message: flagError.message,
1284
+ hint: flagError.hint ?? null,
1285
+ event: 'cli-error',
1286
+ telemetry: { step: 'init_validation', error_code: flagError.errorCode },
1287
+ reason: flagError.reason,
1288
+ resultExtra: { capability: cap },
1289
+ });
1038
1290
  }
1039
- if (target === 'ecs') {
1040
- const previewYmlPath = path.join(dirConfig.targetDir, '.github', 'workflows', 'preview.yml');
1041
- const previewContent = readFileSafe(previewYmlPath);
1042
- if (previewContent) {
1043
- const previewGated = injectPreviewMigrationGate(previewContent, { cmd: migrationCmd, cliVersion: CLI_VERSION });
1044
- if (previewGated) {
1045
- atomicWriteFileSync(previewYmlPath, previewGated);
1046
- console.log(color.green('✅ Wired the preview database migration gate into .github/workflows/preview.yml'));
1047
- } else {
1048
- log.warn(color.yellow('⚠️ Could not wire the preview migration gate: the Comment PR anchor was not found.'));
1049
- }
1050
- }
1291
+ }
1292
+ if (withList.includes('email:ses') && !isInteractive) {
1293
+ const hasDomainFlag = typeof initOptions.domain === 'string' && initOptions.domain.trim() !== '';
1294
+ let domainTfHasDomain = false;
1295
+ if (!hasDomainFlag) {
1296
+ const domainTf = readFileSafe(path.join(targetDir, 'terraform', 'domain.tf'));
1297
+ domainTfHasDomain = Boolean(domainTf && parseDomainTf(domainTf)?.domain);
1298
+ }
1299
+ if (!hasDomainFlag && !domainTfHasDomain) {
1300
+ return refuse({
1301
+ message: '\n✖ No domain for Amazon SES. Pass --domain <domain> or run from a project with terraform/domain.tf.\n',
1302
+ event: 'cli-error',
1303
+ telemetry: { step: 'init_validation', error_code: 'MISSING_SES_DOMAIN' },
1304
+ reason: 'missing-ses-domain',
1305
+ resultExtra: { capability: 'email:ses' },
1306
+ });
1051
1307
  }
1052
1308
  }
1309
+ return { withList, explicitDbEngine, normalizedExplicitTarget };
1310
+ }
1053
1311
 
1054
- if (driftEnabled) {
1055
- // drift.yml rides the manifest + backup like deploy.yml now
1056
- // Re-init backs the old file up and regenerates fresh
1057
- // (current role ARN) instead of silently keeping a stale copy.
1058
- // Hand edits trip refuse-dirty before this point; --force regenerates.
1059
- const drifted = scaffoldDriftWorkflow(dirConfig.targetDir, {
1060
- region: config.region,
1061
- roleArn: buildRoleArn(awsAccountId, buildDeployRoleName(dirConfig.actualProjectName, resourceSuffix)),
1062
- force: initOptions.force,
1063
- });
1064
- if (drifted.ok) {
1065
- console.log(color.green('✅ Scaffolded .github/workflows/drift.yml (scheduled IaC drift detection)'));
1066
- }
1312
+ // Step 2a. Headless wizard gate, target directory resolution, and
1313
+ // existing-tree project-name reuse. Returns { dirConfig } or { refusal }.
1314
+ async function resolveInitWorkdir({ options, isHeadless, headlessOptions, explicitProjectName }) {
1315
+ // Non-interactive wizard gate (sync-ai precedent: bespoke, not the
1316
+ // shared helper — approval flags cannot answer input questions, so
1317
+ // even `init --yes` must refuse here). Without --headless the wizard
1318
+ // always prompts (directory first), so an inferred-headless run (CI,
1319
+ // no TTY) could only abandon — refuse loudly instead. This sits
1320
+ // before the 2b flag validation below because the directory prompt
1321
+ // precedes it; re-running with --headless surfaces any specific
1322
+ // INVALID_* error. No preconfigured exemption: the parser only
1323
+ // exposes flag values in headless mode, so standalone
1324
+ // --preconfigured would silently ignore --framework/--region.
1325
+ if (!isHeadless && resolveHeadless(options)) {
1326
+ return {
1327
+ refusal: await failCommand({
1328
+ message: '\n✖ init needs an interactive terminal to gather project configuration.',
1329
+ hint: ' Re-run with --headless --framework <id> --target <ecs|lambda|static> (plus --region/--with as needed), or run interactively in a terminal.\n',
1330
+ event: 'project_provisioned',
1331
+ telemetry: { projectName: explicitProjectName ?? path.basename(process.cwd()) },
1332
+ errorCode: 'INIT_NON_INTERACTIVE',
1333
+ reason: 'non-interactive',
1334
+ exitCode: 1,
1335
+ }),
1336
+ };
1337
+ }
1338
+ const dirConfig = await getTargetDirectory(isHeadless, headlessOptions, { projectName: explicitProjectName });
1339
+
1340
+ // Re-init over an existing tree keeps the tree's project name: after a
1341
+ // directory rename or copy, re-deriving from the basename would silently
1342
+ // fork every singleton (state bucket, RDS, ECR…) into a parallel stack
1343
+ // while the old one keeps billing. --project-name renames explicitly.
1344
+ const treeProjectName = readTerraformProjectName(dirConfig.targetDir);
1345
+ const sanitizedTreeName = treeProjectName ? sanitizeProjectName(treeProjectName) : null;
1346
+ if (sanitizedTreeName && explicitProjectName && sanitizedTreeName !== dirConfig.actualProjectName) {
1347
+ console.log(color.yellow(`⚠️ --project-name "${dirConfig.actualProjectName}" overrides this tree's project "${treeProjectName}" — the next apply will provision a NEW stack; the "${treeProjectName}" stack is left untouched (and still billing).`));
1348
+ trackEvent('init_project_name_override', { projectName: dirConfig.actualProjectName });
1349
+ } else if (sanitizedTreeName && !explicitProjectName && sanitizedTreeName !== dirConfig.actualProjectName) {
1350
+ console.log(color.yellow(`⚠️ Directory "${path.basename(dirConfig.targetDir)}" doesn't match this tree's project "${sanitizedTreeName}" — keeping "${sanitizedTreeName}" so re-init doesn't fork your infrastructure. Pass --project-name <name> to rename explicitly.`));
1351
+ trackEvent('init_project_name_reused', { projectName: sanitizedTreeName });
1352
+ dirConfig.actualProjectName = sanitizedTreeName;
1067
1353
  }
1354
+ return { dirConfig };
1355
+ }
1068
1356
 
1069
- if (planEnabled) {
1070
- // plan.yml rides the manifest + backup like drift.yml (R1):
1071
- // re-init backs the old file up and regenerates fresh (current
1072
- // role ARN) instead of silently keeping a stale copy.
1073
- const planned = scaffoldPlanWorkflow(dirConfig.targetDir, {
1074
- region: config.region,
1075
- roleArn: buildRoleArn(awsAccountId, buildPreviewRoleName(dirConfig.actualProjectName, resourceSuffix)),
1076
- force: initOptions.force,
1357
+ // Step 1. Silent Pre-flight check: terraform must exist. Keeps the
1358
+ // original fall-through shape (failCommand exits in CLI mode).
1359
+ async function ensureTerraformInstalled() {
1360
+ const hasTerraform = await checkDependency('terraform');
1361
+ if (!hasTerraform) {
1362
+ await failCommand({
1363
+ print: () => {
1364
+ console.error(color.red('✖ Terraform is not installed.'));
1365
+ console.log(color.yellow('Please run "npx grada-run doctor" to check your environment.'));
1366
+ },
1077
1367
  });
1078
- if (planned.ok) {
1079
- console.log(color.green('✅ Scaffolded .github/workflows/plan.yml (Terraform plan on PR)'));
1080
- }
1081
1368
  }
1369
+ }
1082
1370
 
1083
- // 7b2. Restore preserved files over the fresh output, then record
1084
- // content hashes of everything generated above so a later re-run can
1085
- // distinguish pristine output from hand edits (F3), plus the intended
1086
- // compute target (R5) for the target-switch gate. The manifest lands
1087
- // after the restore so secret_keys.json hashes the carried content.
1088
- restoreManagedFiles(dirConfig.targetDir, preservedStash);
1089
- writeInitManifest(dirConfig.targetDir, { target });
1371
+ async function mainStackMain(input = {}) {
1372
+ const options = normalizeOptions(input);
1373
+ const { isHeadless = false } = options;
1374
+ const isPreconfigured = options.isPreconfigured === true || process.argv.includes('--preconfigured');
1375
+ const headlessOptions = normalizeOptions(options.headlessOptions);
1376
+ const initOptions = normalizeOptions(options.initOptions);
1377
+ const isInteractive = !isHeadless && !isPreconfigured;
1378
+ const startTime = Date.now();
1090
1379
 
1091
- // 7c. Print-only stack preview when addons were scaffolded (default
1092
- // no-addon output is untouched).
1093
- if (selectedAddons.length > 0) {
1094
- const parsed = parseTerraformConfig(path.join(dirConfig.targetDir, 'terraform'));
1095
- parsed.projectName = dirConfig.actualProjectName;
1096
- parsed.framework = detectedFramework?.name || config.framework;
1097
- await renderDryRunPreview(parsed, true);
1098
- }
1380
+ // 1. Silent Pre-flight check
1381
+ await ensureTerraformInstalled();
1099
1382
 
1100
- // 8. Telemetry
1101
- trackEvent('project_provisioned', {
1102
- // 1. Core & Context
1103
- projectName: dirConfig.actualProjectName,
1104
- success: true, // funnel outcome: failures emit success:false via failCommand
1105
- cli_version: CLI_VERSION,
1106
- is_headless: isHeadless,
1107
- setup_mode: config.setupType,
1108
- duration_ms: Date.now() - startTime,
1383
+ if (!isHeadless) intro(color.bgCyan(color.black(' grada ☁️ ')));
1109
1384
 
1110
- // 2. Infrastructure Shape
1111
- target,
1112
- framework: config.framework,
1113
- resource_suffix_present: resourceSuffix !== '',
1114
- specific_framework: detectedFramework?.name || config.framework,
1115
- region: config.region,
1116
- size: config.size,
1117
- desired_count: parseInt(config.desiredCount),
1118
- has_database: config.needsDatabase,
1119
- db_engine: config.needsDatabase ? config.dbEngine : 'none',
1120
- has_custom_health_check: config.healthCheckPath !== '/',
1385
+ // 2. Resolve Target & Scan Codebase
1386
+ const explicitProjectName = typeof initOptions.projectName === 'string' && initOptions.projectName.trim() !== ''
1387
+ ? initOptions.projectName.trim()
1388
+ : null;
1389
+ const explicitGitHubRepo = typeof initOptions.githubRepo === 'string' && initOptions.githubRepo.trim() !== ''
1390
+ ? initOptions.githubRepo.trim()
1391
+ : null;
1392
+ // 2a. Headless gate, target directory, tree-name reuse.
1393
+ const workdir = await resolveInitWorkdir({ options, isHeadless, headlessOptions, explicitProjectName });
1394
+ if (workdir.refusal) return workdir.refusal;
1395
+ const { dirConfig } = workdir;
1121
1396
 
1122
- // 3. Advanced Features & PaaS Context
1123
- has_worker: willHaveWorker,
1124
- is_heroku_migration: !!procfile,
1125
- is_vercel_migration: !!vercelRules,
1126
- is_docker_compose: !!dockerCompose,
1127
- has_pr_previews: config.enablePrPreviews,
1128
- ai_assistants_configured: config.aiAssistants || [],
1397
+ // 2b. Fail-fast validation of init composition flags.
1398
+ const validated = await validateInitFlags({ initOptions, headlessOptions, isInteractive, explicitGitHubRepo, targetDir: dirConfig.targetDir });
1399
+ if (validated.refusal) return validated.refusal;
1400
+ const { withList, explicitDbEngine, normalizedExplicitTarget } = validated;
1129
1401
 
1130
- // 4. Dependency-aware composition
1131
- selected_addons: selectedAddons,
1132
- detected_addons: Object.keys(ADDON_REGISTRY).filter((cap) => capabilities.addons[cap]?.detected === true),
1133
- migration_gate_enabled: migrationGateEnabled,
1134
- drift_detection_enabled: driftEnabled,
1135
- plan_on_pr_enabled: planEnabled,
1136
- });
1402
+ // Collision suffix, resolved before any prompt/AWS call/write (and
1403
+ // before backup planning moves the old tree): fresh trees mint, re-init
1404
+ // reuses the rendered value, pre-suffix trees stay '' (zero drift).
1405
+ const resourceSuffix = resolveInitSuffix(dirConfig.targetDir);
1137
1406
 
1138
- s.stop('Infrastructure provisioned successfully!');
1407
+ // Compute target + capability-vs-target policy.
1408
+ const targetResolved = await resolveInitTarget({ isInteractive, normalizedExplicitTarget, withList });
1409
+ if (targetResolved.refusal) return targetResolved.refusal;
1410
+ const { target } = targetResolved;
1139
1411
 
1140
- // 8.5 Configure AI Context
1141
- s.start('Configuring AI workspace rules...');
1142
- const aiContext = { region: config.region, port: config.port, target: config.target };
1143
- const cwd = dirConfig.targetDir;
1412
+ // 2d. Codebase scans.
1413
+ const { detectedFramework, procfile, vercelRules, dockerCompose, capabilities } = scanInitCodebase({ targetDir: dirConfig.targetDir, isHeadless });
1144
1414
 
1145
- if (config.setupType === 'advanced') {
1146
- // --- ADVANCED MODE: Explicitly respect user choices ---
1147
- if (config.aiAssistants.includes('cursor')) {
1148
- const cursorDir = path.join(cwd, '.cursor', 'rules');
1149
- if (!fsSync.existsSync(cursorDir)) fsSync.mkdirSync(cursorDir, { recursive: true });
1150
- fsSync.writeFileSync(path.join(cursorDir, 'grada.mdc'), getCursorRules(aiContext));
1151
- }
1152
- if (config.aiAssistants.includes('roo')) {
1153
- const rooDir = path.join(cwd, '.roo', 'rules');
1154
- if (!fsSync.existsSync(rooDir)) fsSync.mkdirSync(rooDir, { recursive: true });
1155
- fsSync.writeFileSync(path.join(rooDir, 'grada.md'), getBaseRules(aiContext));
1156
- }
1157
- if (config.aiAssistants.includes('trae')) {
1158
- const traeDir = path.join(cwd, '.trae', 'rules');
1159
- if (!fsSync.existsSync(traeDir)) fsSync.mkdirSync(traeDir, { recursive: true });
1160
- injectManagedBlock(path.join(traeDir, 'project_rules.md'), getBaseRules(aiContext), true);
1161
- }
1162
- if (config.aiAssistants.includes('continue')) {
1163
- const promptsDir = path.join(cwd, '.prompts');
1164
- if (!fsSync.existsSync(promptsDir)) fsSync.mkdirSync(promptsDir, { recursive: true });
1165
- fsSync.writeFileSync(path.join(promptsDir, 'grada.prompt'), getBaseRules(aiContext));
1166
- }
1167
- if (config.aiAssistants.includes('windsurf')) {
1168
- injectManagedBlock(path.join(cwd, '.windsurfrules'), getBaseRules(aiContext), true);
1169
- }
1170
- if (config.aiAssistants.includes('copilot')) {
1171
- const copilotPath = path.join(cwd, '.github', 'copilot-instructions.md');
1172
- if (!fsSync.existsSync(path.dirname(copilotPath))) fsSync.mkdirSync(path.dirname(copilotPath), { recursive: true });
1173
- injectManagedBlock(copilotPath, getBaseRules(aiContext), true);
1174
- }
1175
- if (config.aiAssistants.includes('claude')) {
1176
- injectManagedBlock(path.join(cwd, 'CLAUDE.md'), getBaseRules(aiContext), true);
1177
- }
1178
- if (config.aiAssistants.includes('goose')) {
1179
- injectManagedBlock(path.join(cwd, '.goosehints'), getBaseRules(aiContext), true);
1180
- }
1181
- if (config.aiAssistants.includes('aider')) {
1182
- injectManagedBlock(path.join(cwd, '.aider.conf.yml'), getBaseRules(aiContext), false);
1183
- }
1184
- } else {
1185
- // --- QUICKSTART MODE: Silent Auto-Detection ---
1186
- if (fsSync.existsSync(path.join(cwd, '.cursor'))) {
1187
- const cursorDir = path.join(cwd, '.cursor', 'rules');
1188
- if (!fsSync.existsSync(cursorDir)) fsSync.mkdirSync(cursorDir, { recursive: true });
1189
- fsSync.writeFileSync(path.join(cursorDir, 'grada.mdc'), getCursorRules(aiContext));
1190
- }
1191
- if (fsSync.existsSync(path.join(cwd, '.roo')) || fsSync.existsSync(path.join(cwd, '.roorules'))) {
1192
- const rooDir = path.join(cwd, '.roo', 'rules');
1193
- if (!fsSync.existsSync(rooDir)) fsSync.mkdirSync(rooDir, { recursive: true });
1194
- fsSync.writeFileSync(path.join(rooDir, 'grada.md'), getBaseRules(aiContext));
1195
- }
1196
- if (fsSync.existsSync(path.join(cwd, '.trae'))) {
1197
- const traeDir = path.join(cwd, '.trae', 'rules');
1198
- if (!fsSync.existsSync(traeDir)) fsSync.mkdirSync(traeDir, { recursive: true });
1199
- injectManagedBlock(path.join(traeDir, 'project_rules.md'), getBaseRules(aiContext), true);
1200
- }
1201
- if (fsSync.existsSync(path.join(cwd, '.continue')) || fsSync.existsSync(path.join(cwd, '.prompts'))) {
1202
- const promptsDir = path.join(cwd, '.prompts');
1203
- if (!fsSync.existsSync(promptsDir)) fsSync.mkdirSync(promptsDir, { recursive: true });
1204
- fsSync.writeFileSync(path.join(promptsDir, 'grada.prompt'), getBaseRules(aiContext));
1205
- }
1206
- if (fsSync.existsSync(path.join(cwd, '.windsurf')) || fsSync.existsSync(path.join(cwd, '.windsurfrules'))) {
1207
- injectManagedBlock(path.join(cwd, '.windsurfrules'), getBaseRules(aiContext), true);
1208
- }
1415
+ // 3. Gather Configuration & Framework Quirks.
1416
+ const gathered = await gatherInitConfig({ isHeadless, headlessOptions, targetDir: dirConfig.targetDir, detectedFramework, capabilities, explicitDbEngine, target, explicitGitHubRepo, projectName: dirConfig.actualProjectName, procfile, force: initOptions.force === true, isInteractive });
1417
+ if (gathered.refusal) return gathered.refusal;
1418
+ const { config, oidcResolution, oidcTrustSub, djangoWsgi, disableDefaultCI } = gathered;
1209
1419
 
1210
- const copilotPath = path.join(cwd, '.github', 'copilot-instructions.md');
1211
- if (fsSync.existsSync(copilotPath)) injectManagedBlock(copilotPath, getBaseRules(aiContext), true);
1212
- if (fsSync.existsSync(path.join(cwd, 'CLAUDE.md'))) injectManagedBlock(path.join(cwd, 'CLAUDE.md'), getBaseRules(aiContext), true);
1213
- if (fsSync.existsSync(path.join(cwd, '.goosehints'))) injectManagedBlock(path.join(cwd, '.goosehints'), getBaseRules(aiContext), true);
1420
+ // 3b. Dependency-aware composition (worker, migration gate, addons).
1421
+ // Everything here resolves before backups, AWS calls, or file writes.
1422
+ const staticLimits = await applyStaticCompositionLimits({ target, config, detectedFramework, procfile, capabilities });
1423
+ if (staticLimits.refusal) return staticLimits.refusal;
1424
+ const { isStaticSite } = staticLimits;
1425
+ // Worker command.
1426
+ const { workerCommandHcl, willHaveWorker } = await resolveWorkerCommand({ isInteractive, isStaticSite, target, procfile, capabilities, needsDatabase: config.needsDatabase });
1214
1427
 
1215
- if (fsSync.existsSync(path.join(cwd, '.aider.conf.yml'))) {
1216
- injectManagedBlock(path.join(cwd, '.aider.conf.yml'), getBaseRules(aiContext), false);
1217
- } else if (fsSync.existsSync(path.join(cwd, '.aider.model.settings.yml'))) {
1218
- injectManagedBlock(path.join(cwd, '.aider.model.settings.yml'), getBaseRules(aiContext), false);
1219
- }
1220
- }
1221
- s.stop('AI rules configured successfully!');
1428
+ // Pre-deploy migration gate.
1429
+ const migrationResolved = await resolveMigrationGate({ initOptions, capabilities, target, needsDatabase: config.needsDatabase, framework: config.framework, isInteractive, targetDir: dirConfig.targetDir, projectName: dirConfig.actualProjectName });
1430
+ if (migrationResolved.refusal) return migrationResolved.refusal;
1431
+ const { migrationCmd, migrationCmdSource, migrationGateEnabled } = migrationResolved;
1222
1432
 
1223
- // 9. Output
1224
- let frameworkWarnings = '';
1433
+ // CI opt-ins: drift detection + plan-on-PR.
1434
+ const { driftEnabled, planEnabled } = await resolveCiOptIns({ initOptions, isInteractive });
1225
1435
 
1226
- if (!isPreconfigured && !(config.framework === 'static' && detectedFramework?.buildDir)) {
1227
- frameworkWarnings = getFrameworkWarning(config.framework);
1228
- }
1436
+ // Addon selection + per-addon options.
1437
+ const addonsResolved = await resolveInitAddons({ isInteractive, isStaticSite, withList, capabilities, initOptions, targetDir: dirConfig.targetDir, region: config.region });
1438
+ if (addonsResolved.refusal) return addonsResolved.refusal;
1439
+ const { selectedAddons, resolvedByCap } = addonsResolved;
1229
1440
 
1230
- // 9b. Post-init capability hints (interactive only, so headless
1231
- // stdout stays byte-identical).
1232
- if (isInteractive) {
1233
- const upcoming = capabilities.upcomingHints;
1234
- if (upcoming.vector) {
1235
- console.log(color.dim(' 💡 Vector-search dependencies detected: managed pgvector support is coming soon.'));
1236
- }
1237
- // Static targets refuse `add cron` (no compute) — don't send
1238
- // static users down a dead end.
1239
- if (upcoming.cron && target !== 'static') {
1240
- console.log(color.dim(' 💡 Scheduled-task dependencies detected: scaffold a schedule with "grada add cron".'));
1241
- }
1242
- if (upcoming.mysql) {
1243
- console.log(color.dim(' 💡 MySQL dependencies detected: RDS currently provisions PostgreSQL; MySQL support is coming soon.'));
1244
- }
1245
- }
1441
+ // 3.5 Docker Compose Overrides.
1442
+ const { composeForMerge, composeWebName } = mergeComposeOverrides({ dockerCompose, config, projectName: dirConfig.actualProjectName, isHeadless });
1246
1443
 
1247
- // ORM runner matrix: when the gate was auto-wired to a mapped ORM
1248
- // command, say which one and what the user must guarantee (the
1249
- // bundle path / production dependency), while the run is fresh.
1250
- if (migrationGateEnabled && migrationCmdSource === 'detected') {
1251
- const ormMapped = detectOrmMigrationCommand(dirConfig.targetDir);
1252
- if (ormMapped && ormMapped.command === migrationCmd) {
1253
- const ormWarning = ormMapped.orm === 'drizzle'
1254
- ? 'Detected Drizzle ORM. Configured migration gate to use \'node ./dist/migrate.cjs\'. Ensure your build script bundles your migrator to this path.'
1255
- : 'Detected Prisma. Configured migration gate to run via \'node_modules/prisma/build/index.js\'. Ensure Prisma is in your production dependencies.';
1256
- log.warn(color.yellow(`⚠️ ${ormWarning}`));
1257
- }
1258
- }
1444
+ // 4. Framework Migration Checks (Vercel Escape Hatch)
1445
+ warnMigrationMismatches({ target, vercelRules, config, detectedFramework, targetDir: dirConfig.targetDir });
1259
1446
 
1260
- const isGitInitialized = fsSync.existsSync(path.join(dirConfig.targetDir, '.git'));
1261
- const needsCd = dirConfig.projectName && dirConfig.projectName !== '.';
1262
- const applyStep = needsCd ? `cd ${dirConfig.projectName} && npx --yes grada-run apply` : 'npx --yes grada-run apply';
1263
- const gitInstructions = isGitInitialized
1264
- ? `git add . && git commit -m "chore: add AWS infrastructure and CI/CD" && git push`
1265
- : `git init && git add . && git commit -m "chore: add AWS infrastructure and CI/CD" && git branch -M ${config.branch} && git remote add origin https://github.com/your-username/your-repo.git && git push -u origin ${config.branch}`;
1447
+ // 5. Calculate Derived Values
1448
+ const { cpu, memory, computeTier, estimatedCost, buildDir } = deriveInitValues({ config, willHaveWorker, target, selectedAddons, detectedFramework });
1266
1449
 
1267
- let docsTip = '';
1268
- if (procfile) {
1269
- docsTip = `\n ${color.blue('📘 Read the Heroku Migration Guide:')} ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/migrations/heroku-procfile-to-aws.md')}`;
1270
- } else if (config.needsDatabase) {
1271
- docsTip = `\n ${color.blue('📘 Read the Database Connections Guide:')} ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/database-connections.md')}`;
1272
- }
1450
+ // 6. Existing-file plan, state provisioning, backup.
1451
+ const fileHandling = await planInitFileHandling({ targetDir: dirConfig.targetDir, isHeadless, force: initOptions.force });
1452
+ if (fileHandling.refusal) return fileHandling.refusal;
1453
+ const { existingFilesPlan, preservedStash } = fileHandling;
1273
1454
 
1274
- outro(`${color.green('✅ Templates generated!')} ${color.blue('🛡️ DevSecOps scanning enabled.')}
1275
- ${frameworkWarnings ? `\n ${frameworkWarnings}` : ''}
1276
- ${color.yellow('Next steps:')}
1277
- 1. ${color.cyan(applyStep)}
1278
- 2. ${color.cyan(gitInstructions)}
1279
- ${color.magenta('🚀 Need help?')} ${color.underline('https://calendly.com/anton-codes-iac/15min')}`);
1455
+ const s = spinner();
1456
+ s.start('Provisioning infrastructure...');
1280
1457
 
1281
- if (offlineScaffold) {
1282
- // Pass the exact backend bucket (suffix included) — recomputing
1283
- // from the bare project name prints a bucket terraform never uses.
1284
- // Step 2 names only emitted workflows: preview/teardown render
1285
- // with PR previews, drift only when enabled.
1286
- printOfflineChecklist({
1287
- bucket: stateBucketName,
1288
- region: config.region,
1289
- workflows: [
1290
- 'deploy',
1291
- ...(config.enablePrPreviews ? ['preview', 'teardown'] : []),
1292
- ...(driftEnabled ? ['drift'] : []),
1293
- ],
1294
- });
1295
- }
1458
+ const offlineScaffold = initOptions.offline === true;
1459
+ const provisioned = await provisionInitState({ s, initOptions, isHeadless, targetDir: dirConfig.targetDir, projectName: dirConfig.actualProjectName, resourceSuffix, region: config.region, existingFilesPlan, offlineScaffold });
1460
+ if (provisioned.refusal) return provisioned.refusal;
1461
+ const { awsAccountId, stateBucketName } = provisioned;
1462
+
1463
+ // 7. Synthesize Templates
1464
+ s.message('Synthesizing Terraform templates...');
1465
+ await synthesizeInitTemplates({ dirConfig, config, target, resourceSuffix, cpu, memory, computeTier, estimatedCost, buildDir, stateBucketName, awsAccountId, djangoWsgi, disableDefaultCI, procfile, vercelRules, composeForMerge, composeWebName, workerCommandHcl, oidcTrustSub, oidcTreeBranches: oidcResolution.treeBranches });
1466
+
1467
+ // 7b. Addons, migration gate, drift + plan workflows.
1468
+ await wireInitWorkflows({ targetDir: dirConfig.targetDir, projectName: dirConfig.actualProjectName, resourceSuffix, region: config.region, dbEngine: config.dbEngine, awsAccountId, selectedAddons, resolvedByCap, migrationGateEnabled, migrationCmd, target, driftEnabled, planEnabled, force: initOptions.force });
1469
+
1470
+ // 7b2 + 7c. Restore, manifest, addon preview.
1471
+ await finalizeInitTree({ dirConfig, target, preservedStash, selectedAddons, detectedFramework, config });
1472
+
1473
+ // 8. Telemetry
1474
+ trackProvisionedTelemetry({ projectName: dirConfig.actualProjectName, isHeadless, startTime, target, config, resourceSuffix, detectedFramework, willHaveWorker, procfile, vercelRules, dockerCompose, capabilities, selectedAddons, migrationGateEnabled, driftEnabled, planEnabled });
1475
+
1476
+ s.stop('Infrastructure provisioned successfully!');
1477
+
1478
+ // 8.5 Configure AI Context
1479
+ s.start('Configuring AI workspace rules...');
1480
+ configureAiRules({ targetDir: dirConfig.targetDir, config });
1481
+ s.stop('AI rules configured successfully!');
1482
+
1483
+ // 9. Output
1484
+ printInitOutput({ isPreconfigured, config, detectedFramework, isInteractive, capabilities, target, migrationGateEnabled, migrationCmdSource, migrationCmd, dirConfig, offlineScaffold, procfile, stateBucketName, driftEnabled });
1296
1485
 
1297
1486
  await flushTelemetry();
1298
1487
  }