grada-run 0.40.12 → 0.40.14

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.
@@ -499,6 +499,64 @@ function isSameServerConfig(entry) {
499
499
  && entry.args.every((arg, index) => arg === MCP_SERVER_CONFIG.args[index]);
500
500
  }
501
501
 
502
+ // Editors whose config files are JSONC (comments allowed). A commented
503
+ // file from any other editor is genuinely corrupt.
504
+ const JSONC_EDITORS = new Set(['zed', 'vscode', 'gemini-cli']);
505
+
506
+ // Strips `//` and `/* */` comments for detection only (never written
507
+ // back): string contents — including `//` inside URLs — are preserved.
508
+ function stripJsonComments(text) {
509
+ let out = '';
510
+ let i = 0;
511
+ let inString = false;
512
+ let stringQuote = '';
513
+ while (i < text.length) {
514
+ const ch = text[i];
515
+ const next = text[i + 1];
516
+ if (inString) {
517
+ out += ch;
518
+ if (ch === '\\') {
519
+ out += next || '';
520
+ i += 2;
521
+ continue;
522
+ }
523
+ if (ch === stringQuote) inString = false;
524
+ i += 1;
525
+ continue;
526
+ }
527
+ if (ch === '"' || ch === "'") {
528
+ inString = true;
529
+ stringQuote = ch;
530
+ out += ch;
531
+ i += 1;
532
+ continue;
533
+ }
534
+ if (ch === '/' && next === '/') {
535
+ while (i < text.length && text[i] !== '\n') i += 1;
536
+ continue;
537
+ }
538
+ if (ch === '/' && next === '*') {
539
+ i += 2;
540
+ while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) i += 1;
541
+ i += 2;
542
+ continue;
543
+ }
544
+ out += ch;
545
+ i += 1;
546
+ }
547
+ return out;
548
+ }
549
+
550
+ function tryParseJsoncObject(text) {
551
+ try {
552
+ const parsed = JSON.parse(stripJsonComments(String(text ?? '')));
553
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
554
+ return parsed;
555
+ } catch {
556
+ return null;
557
+ }
558
+ }
559
+
502
560
  // Writes the Grada MCP server entry into an editor's config file,
503
561
  // preserving every existing key and server. `homeDir` is injectable so
504
562
  // tests never touch the real home directory. Never throws and never
@@ -536,6 +594,22 @@ export function installMcpConfig(editor, { homeDir = safeHomedir(), platform = o
536
594
  }
537
595
  }
538
596
  } catch {
597
+ // A commented file is healthy for JSONC editors: say so and hand
598
+ // over the exact block to paste instead of misdiagnosing it.
599
+ if (JSONC_EDITORS.has(normalized) && fsSync.existsSync(target.path)) {
600
+ const jsonc = tryParseJsoncObject(fsSync.readFileSync(target.path, 'utf-8'));
601
+ if (jsonc) {
602
+ const block = JSON.stringify({ grada: { ...MCP_SERVER_CONFIG, args: [...MCP_SERVER_CONFIG.args] } }, null, 4);
603
+ return {
604
+ ok: false,
605
+ reason: 'jsonc-config',
606
+ errorCode: 'MCP_INSTALL_JSONC_CONFIG',
607
+ editor: normalized,
608
+ path: target.path,
609
+ message: `\n✖ ${target.path} uses JSONC (comments), which grada cannot edit without destroying them — your file is untouched.\nAdd the Grada server by hand under "${target.key}":\n\n${block}\n`,
610
+ };
611
+ }
612
+ }
539
613
  return {
540
614
  ok: false,
541
615
  reason: 'unreadable-config',
@@ -8,7 +8,7 @@ import {
8
8
  import color from 'picocolors';
9
9
  import { intro, outro, spinner, select, isCancel } from '@clack/prompts';
10
10
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
11
- import { failCommand, failAwsError, failProjectNotInitialized } from '../utils/command.js';
11
+ import { failCommand, failAwsError, failProjectNotInitialized, refuseIfNonInteractive } from '../utils/command.js';
12
12
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
13
13
  import { isAuthError, handleAwsAuthError, resolveClient } from '../utils/aws.js';
14
14
  import { resolveRegion, resolveProjectName, resolveCluster, resolveService, readFileSafe, resolveWorkspaceSuffix, resolveCwd, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
@@ -196,9 +196,24 @@ async function runRollbackMain(input = {}) {
196
196
  }
197
197
  targetTaskDefArn = descResp.taskDefinition.taskDefinitionArn;
198
198
  targetRevisionNum = String(descResp.taskDefinition.revision);
199
+ // Explicit family/ARN input escapes the numeric path's forced
200
+ // family scoping: refuse to re-point the service at a foreign
201
+ // family's task definition (fail closed when family is absent).
202
+ if (descResp.taskDefinition.family !== family) {
203
+ s.stop(color.red('Foreign task definition family.'));
204
+ return failCommand({
205
+ message: `\n✖ Task definition "${targetInput}" belongs to family "${descResp.taskDefinition.family ?? 'unknown'}", not "${family}". Rollback stays within the service's own family.`,
206
+ hint: 'List recent revisions with: aws ecs list-task-definitions --family-prefix ' + family + ` --region ${region}\n`,
207
+ event: 'rollback_run',
208
+ telemetry: { projectName, error_code: 'REVISION_FAMILY_MISMATCH' },
209
+ reason: 'revision-family-mismatch',
210
+ resultExtra: { cluster, service, region },
211
+ exitCode: 1,
212
+ });
213
+ }
199
214
  // A request for the currently deployed revision warns instead
200
215
  // of silently redeploying it.
201
- if (Number(targetRevisionNum) === currentRevNum) {
216
+ if (targetTaskDefArn === currentTaskDefArn) {
202
217
  s.stop(color.yellow('Already on the requested revision.'));
203
218
  trackEvent('rollback_current_revision_warned', { projectName, revision: targetRevisionNum });
204
219
  return failCommand({
@@ -230,6 +245,17 @@ async function runRollbackMain(input = {}) {
230
245
  });
231
246
  }
232
247
 
248
+ // Inferred-headless runs (CI, no TTY) refuse instead of
249
+ // silently auto-picking: an explicit revision (Case A) or an
250
+ // explicit --headless flag still bypasses this gate.
251
+ const refused = await refuseIfNonInteractive(options, {
252
+ message: `\n✖ rollback needs a revision before rolling back.`,
253
+ hint: ' Re-run with an explicit revision (rollback 12) or --headless to take the newest previous revision non-interactively.\n',
254
+ event: 'rollback_run',
255
+ telemetry: { projectName },
256
+ errorCode: 'ROLLBACK_NON_INTERACTIVE',
257
+ });
258
+ if (refused) return refused;
233
259
  if (headless) {
234
260
  targetTaskDefArn = pickNewestEligible(eligibleArns);
235
261
  targetRevisionNum = targetTaskDefArn.split(':').pop();
@@ -6,7 +6,7 @@ import { spinner, confirm, outro, isCancel } from '@clack/prompts';
6
6
  import color from 'picocolors';
7
7
  import path from 'path';
8
8
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
9
- import { failCommand } from '../utils/command.js';
9
+ import { failCommand, refuseIfNonInteractive } from '../utils/command.js';
10
10
  import { atomicWriteFile } from '../utils/atomic-write.js';
11
11
  import { handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
12
12
  import { readTerraformComputeTarget, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
@@ -149,6 +149,44 @@ export function diffSecretsEnvs(localSecrets = {}, remoteSecrets = {}) {
149
149
  return { missingLocally, mismatched, untrackedLocally };
150
150
  }
151
151
 
152
+ // Shared failure tail for push/pull/audit: identical telemetry stamps,
153
+ // not-found guidance, auth branch, and spinner/exit routing, so the
154
+ // three subcommands cannot drift apart again.
155
+ async function handleSecretsCatch({
156
+ error,
157
+ event,
158
+ verb,
159
+ s,
160
+ opts,
161
+ projectName,
162
+ notFoundMessage,
163
+ notFoundGuidance,
164
+ spinnerStopped = false,
165
+ stackTraceOnTypeError = false,
166
+ }) {
167
+ await trackFailure(event, {
168
+ projectName,
169
+ error_code: error.code || error.name || 'UNKNOWN',
170
+ error_message: error.message,
171
+ ...(stackTraceOnTypeError ? { stack_trace: error.name === 'TypeError' ? error.stack : undefined } : {}),
172
+ });
173
+ if (error.name === 'ResourceNotFoundException') {
174
+ s.stop(color.red(notFoundMessage));
175
+ console.log(color.yellow('\n💡 Next Step:'));
176
+ for (const line of notFoundGuidance) console.log(line);
177
+ } else if (handleAuthErrorBranch(error, s, opts)) {
178
+ return;
179
+ } else if (spinnerStopped) {
180
+ // The spinner already stopped, so its stop is a no-op —
181
+ // route the message through the failure stamp instead.
182
+ return failCommand({ message: `❌ Failed to ${verb} secrets: ${error.message}`, exitCode: 1 });
183
+ } else {
184
+ s.stop(`❌ Failed to ${verb} secrets: ${error.message}`);
185
+ }
186
+
187
+ return failCommand({ exitCode: 1 });
188
+ }
189
+
152
190
  export function resolveEcsCluster(projectName, options = {}) {
153
191
  if (typeof options.cluster === 'string' && options.cluster.trim()) return options.cluster.trim();
154
192
  if (typeof process.env.ECS_CLUSTER === 'string' && process.env.ECS_CLUSTER.trim()) {
@@ -226,6 +264,14 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
226
264
  },
227
265
  });
228
266
  }
267
+ const refused = await refuseIfNonInteractive(opts, {
268
+ message: `\n✖ secrets push needs an .env file before pushing.`,
269
+ hint: ' Generate the .env file before pushing, or run interactively to create an empty one.\n',
270
+ event: 'secrets_pushed',
271
+ telemetry: { projectName: resolvedProjectName },
272
+ errorCode: 'SECRETS_NON_INTERACTIVE',
273
+ });
274
+ if (refused) return refused;
229
275
  const confirmed = await confirm({
230
276
  message: `Would you like to create an empty ${resolvedFilePath} file now to get started?`,
231
277
  });
@@ -335,6 +381,14 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
335
381
  });
336
382
  return { keysChanged: false, restarted: false };
337
383
  }
384
+ const refused = await refuseIfNonInteractive(opts, {
385
+ message: `\n✖ secrets push needs approval before triggering the ECS restart.`,
386
+ hint: ' Re-run with --headless to skip the restart non-interactively (values apply on the next deployment), or run interactively to decide.\n',
387
+ event: 'secrets_pushed',
388
+ telemetry: { projectName: resolvedProjectName },
389
+ errorCode: 'SECRETS_NON_INTERACTIVE',
390
+ });
391
+ if (refused) return refused;
338
392
  const shouldRestart = await confirm({
339
393
  message: 'Keys are unchanged. Trigger a rolling ECS restart to apply new values immediately?',
340
394
  initialValue: false,
@@ -377,24 +431,20 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
377
431
  return { keysChanged };
378
432
 
379
433
  } catch (error) {
380
- await trackFailure('secrets_pushed', {
434
+ return handleSecretsCatch({
435
+ error,
436
+ event: 'secrets_pushed',
437
+ verb: 'push',
438
+ s,
439
+ opts,
381
440
  projectName: resolvedProjectName,
382
- error_code: error.code || error.name || 'UNKNOWN',
383
- error_message: error.message,
384
- stack_trace: error.name === 'TypeError' ? error.stack : undefined
441
+ notFoundMessage: `❌ Secrets Vault "${secretVaultId(resolvedProjectName)}" does not exist in AWS yet.`,
442
+ notFoundGuidance: [
443
+ `Run ${color.cyan('npx --yes grada-run apply')} first to provision the infrastructure and Secrets Manager vault.`,
444
+ `Once applied, run ${color.cyan(`npx grada-run secrets push ${resolvedFilePath}`)} to upload your environment variables.\n`,
445
+ ],
446
+ stackTraceOnTypeError: true,
385
447
  });
386
- if (error.name === 'ResourceNotFoundException') {
387
- s.stop(color.red(`❌ Secrets Vault "${secretVaultId(resolvedProjectName)}" does not exist in AWS yet.`));
388
- console.log(color.yellow('\n💡 Next Step:'));
389
- console.log(`Run ${color.cyan('npx --yes grada-run apply')} first to provision the infrastructure and Secrets Manager vault.`);
390
- console.log(`Once applied, run ${color.cyan(`npx grada-run secrets push ${resolvedFilePath}`)} to upload your environment variables.\n`);
391
- } else if (handleAuthErrorBranch(error, s, opts)) {
392
- return;
393
- } else {
394
- s.stop(`❌ Failed to push secrets: ${error.message}`);
395
- }
396
-
397
- return failCommand({ exitCode: 1 });
398
448
  }
399
449
  }
400
450
 
@@ -467,6 +517,14 @@ async function pullSecretsMain(envFilePath, projectName, options = {}) {
467
517
  if (isHeadless) {
468
518
  overwrite = true;
469
519
  } else {
520
+ const refused = await refuseIfNonInteractive(opts, {
521
+ message: `\n✖ secrets pull needs approval before overwriting local values.`,
522
+ hint: ' Re-run with --headless to overwrite non-interactively, or run interactively to review conflicts.\n',
523
+ event: 'secrets_pull',
524
+ telemetry: { projectName: resolvedProjectName },
525
+ errorCode: 'SECRETS_NON_INTERACTIVE',
526
+ });
527
+ if (refused) return refused;
470
528
  const answer = await confirm({
471
529
  message: 'Conflicting variables found. Overwrite local values with remote?',
472
530
  initialValue: false,
@@ -512,26 +570,19 @@ async function pullSecretsMain(envFilePath, projectName, options = {}) {
512
570
 
513
571
  return { synced: remoteKeys.length, file: resolvedFilePath, overwritten: overwrite, conflicts: mismatched };
514
572
  } catch (error) {
515
- await trackFailure('secrets_pull', {
573
+ return handleSecretsCatch({
574
+ error,
575
+ event: 'secrets_pull',
576
+ verb: 'pull',
577
+ s,
578
+ opts,
516
579
  projectName: resolvedProjectName,
517
- error_code: error.code || error.name || 'UNKNOWN',
518
- error_message: error.message,
580
+ notFoundMessage: `❌ No remote secrets found for "${secretVaultId(resolvedProjectName)}".`,
581
+ notFoundGuidance: [
582
+ `Run ${color.cyan(`npx grada-run secrets push ${resolvedFilePath}`)} first to upload your environment variables.\n`,
583
+ ],
584
+ spinnerStopped: remoteFetched,
519
585
  });
520
- if (error.name === 'ResourceNotFoundException') {
521
- s.stop(color.red(`❌ No remote secrets found for "${secretVaultId(resolvedProjectName)}".`));
522
- console.log(color.yellow('\n💡 Next Step:'));
523
- console.log(`Run ${color.cyan(`npx grada-run secrets push ${resolvedFilePath}`)} first to upload your environment variables.\n`);
524
- } else if (handleAuthErrorBranch(error, s, opts)) {
525
- return;
526
- } else if (remoteFetched) {
527
- // The spinner already stopped, so its stop is a no-op —
528
- // route the message through the failure stamp instead.
529
- return failCommand({ message: `❌ Failed to pull secrets: ${error.message}`, exitCode: 1 });
530
- } else {
531
- s.stop(`❌ Failed to pull secrets: ${error.message}`);
532
- }
533
-
534
- return failCommand({ exitCode: 1 });
535
586
  }
536
587
  }
537
588
 
@@ -618,21 +669,17 @@ async function auditSecretsMain(envFilePath, projectName, options = {}) {
618
669
 
619
670
  return { missingLocally, mismatched, untrackedLocally, driftCount };
620
671
  } catch (error) {
621
- await trackFailure('secrets_audit', {
672
+ return handleSecretsCatch({
673
+ error,
674
+ event: 'secrets_audit',
675
+ verb: 'audit',
676
+ s,
677
+ opts,
622
678
  projectName: resolvedProjectName,
623
- error_code: error.code || error.name || 'UNKNOWN',
624
- error_message: error.message,
679
+ notFoundMessage: `❌ No remote secrets found for "${secretVaultId(resolvedProjectName)}".`,
680
+ notFoundGuidance: [
681
+ `Run ${color.cyan(`npx grada-run secrets push ${resolvedFilePath}`)} first to upload your environment variables.\n`,
682
+ ],
625
683
  });
626
- if (error.name === 'ResourceNotFoundException') {
627
- s.stop(color.red(`❌ No remote secrets found for "${secretVaultId(resolvedProjectName)}".`));
628
- console.log(color.yellow('\n💡 Next Step:'));
629
- console.log(`Run ${color.cyan(`npx grada-run secrets push ${resolvedFilePath}`)} first to upload your environment variables.\n`);
630
- } else if (handleAuthErrorBranch(error, s, opts)) {
631
- return;
632
- } else {
633
- s.stop(`❌ Failed to audit secrets: ${error.message}`);
634
- }
635
-
636
- return failCommand({ exitCode: 1 });
637
684
  }
638
685
  }
@@ -5,10 +5,10 @@ import { RDSClient, StopDBInstanceCommand, StopDBClusterCommand } from '@aws-sdk
5
5
  import color from 'picocolors';
6
6
  import { intro, outro, spinner, confirm, cancel } from '@clack/prompts';
7
7
  import { trackEvent, trackSuccess, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
8
- import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized } from '../utils/command.js';
8
+ import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized, refuseIfNonInteractive, shouldAutoApprove } from '../utils/command.js';
9
9
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
10
10
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
11
- import { resolveRegion, resolveProjectName, resolveHeadless, resolveCwd, readTerraformComputeTarget } from '../utils/resolvers.js';
11
+ import { resolveRegion, resolveProjectName, resolveCwd, readTerraformComputeTarget } from '../utils/resolvers.js';
12
12
  import { requireManagedTree } from '../utils/terraform-metadata.js';
13
13
  import { findDbTarget } from '../utils/rds.js';
14
14
  import { fetchActiveService } from '../utils/ecs.js';
@@ -82,7 +82,6 @@ async function runSleepMain(input = {}) {
82
82
  const computeTarget = readTerraformComputeTarget(cwd);
83
83
  const isLambda = computeTarget === 'lambda';
84
84
  const isStatic = computeTarget === 'static';
85
- const headless = resolveHeadless(options);
86
85
  const skipDb = options.skipDb === true || options.skipDb === 'true';
87
86
  const confirmed = options.yes === true || options.yes === 'true'
88
87
  || options.force === true || options.force === 'true';
@@ -173,18 +172,18 @@ async function runSleepMain(input = {}) {
173
172
  // Safety guard: sleeping the default (production) environment takes the
174
173
  // web service offline, so it needs an explicit confirmation.
175
174
  if (target.requiresConfirm && !confirmed) {
176
- if (headless) {
177
- return failCommand({
178
- message: '\n✖ Sleeping the default environment requires confirmation. Re-run with --yes.\n',
175
+ if (!shouldAutoApprove(options)) {
176
+ const refused = await refuseIfNonInteractive(options, {
177
+ message: `\n✖ sleep needs confirmation before putting the default environment to sleep.`,
178
+ hint: ' Re-run with --yes to sleep non-interactively.\n',
179
179
  event: 'sleep_run',
180
- telemetry: { projectName, env_kind: target.envKind },
181
- errorCode: 'CONFIRMATION_REQUIRED',
182
- reason: 'confirmation-required',
183
- resultExtra: { cluster: target.cluster, region },
180
+ telemetry: { projectName },
181
+ errorCode: 'SLEEP_NON_INTERACTIVE',
184
182
  });
183
+ if (refused) return refused;
185
184
  }
186
185
  console.log(color.yellow('\n⚠ This will take the web service offline until you run "grada wake".'));
187
- const answer = await confirm({ message: SLEEP_CONFIRM_MESSAGE, initialValue: false });
186
+ const answer = shouldAutoApprove(options) ? true : await confirm({ message: SLEEP_CONFIRM_MESSAGE, initialValue: false });
188
187
  if (answer !== true) {
189
188
  cancel('Cancelled. Nothing was changed.');
190
189
  return { ok: false, reason: 'cancelled', cluster: target.cluster, region };
@@ -4,7 +4,7 @@ import { intro, outro, spinner, log } from '@clack/prompts';
4
4
  import color from 'picocolors';
5
5
  import { getAiAssistants } from '../utils/prompts.js';
6
6
  import { getBaseRules, getCursorRules, injectManagedBlock } from '../utils/ai-rules.js';
7
- import { readTerraformComputeTarget } from '../utils/resolvers.js';
7
+ import { readTerraformComputeTarget, resolveHeadless } from '../utils/resolvers.js';
8
8
  import { trackEvent, flushTelemetry, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
9
9
  import { failCommand } from '../utils/command.js';
10
10
 
@@ -29,18 +29,31 @@ function getProjectContext(cwd) {
29
29
 
30
30
  // Programmatic entry wrapper: stamps cli_command for telemetry on every
31
31
  // invocation path, including direct imports that bypass bin/cli.js and MCP.
32
- export async function syncAi() {
32
+ export async function syncAi(options = {}) {
33
33
  setActiveCommandName('sync_ai');
34
34
  try {
35
- return await syncAiMain();
35
+ return await syncAiMain(options);
36
36
  } finally {
37
37
  resetActiveCommandName();
38
38
  }
39
39
  }
40
40
 
41
- async function syncAiMain() {
41
+ async function syncAiMain(options = {}) {
42
42
  intro(color.bgCyan(color.black(' grada sync-ai 🤖 ')));
43
43
 
44
+ // Assistant selection is prompt-only: refuse loudly without a TTY
45
+ // instead of abandoning the prompt and "succeeding" with nothing.
46
+ if (resolveHeadless(options)) {
47
+ return failCommand({
48
+ message: '\n✖ sync-ai needs an interactive terminal to choose assistants.',
49
+ hint: ' Run it in a terminal, or re-run init to regenerate rules non-interactively.\n',
50
+ event: 'sync_ai',
51
+ errorCode: 'SYNC_AI_NON_INTERACTIVE',
52
+ reason: 'non-interactive',
53
+ exitCode: 1,
54
+ });
55
+ }
56
+
44
57
  const assistants = await getAiAssistants();
45
58
 
46
59
  if (!assistants || assistants.length === 0) {
@@ -81,7 +94,7 @@ async function syncAiMain() {
81
94
  }
82
95
 
83
96
  if (assistants.includes('windsurf')) {
84
- injectManagedBlock(path.join(cwd, '.windsurfrules'), getBaseRules(context), false);
97
+ injectManagedBlock(path.join(cwd, '.windsurfrules'), getBaseRules(context), true);
85
98
  }
86
99
 
87
100
  if (assistants.includes('copilot')) {
@@ -73,9 +73,19 @@ export function injectManagedBlock(filePath, content, isMarkdown = true) {
73
73
  // (Markers carry no regex metacharacters, so direct interpolation
74
74
  // is safe.)
75
75
  const regex = new RegExp(`\\n?(?:${beginMarker}|${legacyBeginMarker})[\\s\\S]*?(?:${endMarker}|${legacyEndMarker})\\n?`);
76
+ // A file whose marker style changed (e.g. windsurf migrating from
77
+ // hash to HTML comments) carries the other style's block: replace
78
+ // that too instead of appending a second block.
79
+ const otherBegin = isMarkdown ? '# BEGIN GRADA CONTEXT' : '<!-- BEGIN GRADA CONTEXT -->';
80
+ const otherEnd = isMarkdown ? '# END GRADA CONTEXT' : '<!-- END GRADA CONTEXT -->';
81
+ const otherLegacyBegin = isMarkdown ? '# BEGIN DEPLOY-STACK CONTEXT' : '<!-- BEGIN DEPLOY-STACK CONTEXT -->';
82
+ const otherLegacyEnd = isMarkdown ? '# END DEPLOY-STACK CONTEXT' : '<!-- END DEPLOY-STACK CONTEXT -->';
83
+ const otherRegex = new RegExp(`\\n?(?:${otherBegin}|${otherLegacyBegin})[\\s\\S]*?(?:${otherEnd}|${otherLegacyEnd})\\n?`);
76
84
 
77
85
  if (regex.test(fileContent)) {
78
86
  fileContent = fileContent.replace(regex, block); // Replace our old rules
87
+ } else if (otherRegex.test(fileContent)) {
88
+ fileContent = fileContent.replace(otherRegex, block); // Replace the other style's block
79
89
  } else {
80
90
  fileContent = fileContent.trim() + '\n' + block; // Append to bottom
81
91
  }
@@ -1,6 +1,7 @@
1
1
  import color from 'picocolors';
2
2
  import { trackEvent, trackFailure, flushTelemetry } from '../core/telemetry.js';
3
3
  import { normalizeOptions } from './args.js';
4
+ import { resolveHeadless } from './resolvers.js';
4
5
 
5
6
  // True when a destructive confirm must be skipped: explicit approval flags
6
7
  // (--auto-approve, --yes) or explicit headless mode. Deliberately checks
@@ -25,6 +26,32 @@ export function isProgrammaticCall(options = {}) {
25
26
  );
26
27
  }
27
28
 
29
+ // Non-interactive prompt gate shared by every command. When the caller is
30
+ // headless (explicit flag, CI, or no TTY) but passed no approval flag, an
31
+ // upcoming prompt could only abandon — refuse loudly with a named error
32
+ // instead of silently skipping. Returns the failure result, or null when
33
+ // the command may proceed (approval flags and real TTYs always proceed).
34
+ // Callers place one gate after arg validation, before the first prompt:
35
+ //
36
+ // const refused = await refuseIfNonInteractive(options, { message, hint, event, telemetry, errorCode });
37
+ // if (refused) return refused;
38
+ export async function refuseIfNonInteractive(options = {}, spec = {}) {
39
+ const opts = normalizeOptions(options);
40
+ if (shouldAutoApprove(opts) || !resolveHeadless(opts)) return null;
41
+ const { message, hint, event, telemetry, errorCode, resultExtra } = spec;
42
+ return failCommand({
43
+ noExit: isProgrammaticCall(opts),
44
+ message,
45
+ hint,
46
+ event,
47
+ telemetry,
48
+ errorCode,
49
+ reason: 'non-interactive',
50
+ resultExtra,
51
+ exitCode: 1,
52
+ });
53
+ }
54
+
28
55
  function paint(tone, fallback) {
29
56
  return typeof color[tone] === 'function' ? color[tone] : fallback;
30
57
  }
package/src/utils/ecs.js CHANGED
@@ -33,6 +33,36 @@ export async function fetchActiveService(ecsClient, clusterName, serviceName) {
33
33
  return service;
34
34
  }
35
35
 
36
+ // `startedAt` is set when the task actually starts running. `createdAt`
37
+ // predates provisioning, so it must never stand in for uptime — a task
38
+ // without `startedAt` has not run yet and fails closed to 0.
39
+ export function taskStartedAtMs(task) {
40
+ const stamp = task?.startedAt;
41
+ if (stamp === undefined || stamp === null) return 0;
42
+ return new Date(stamp).getTime() || 0;
43
+ }
44
+
45
+ // Newest actually-RUNNING task from a described batch.
46
+ // ListTasks({ desiredStatus: 'RUNNING' }) also returns tasks still
47
+ // PROVISIONING/PENDING toward that goal, and its order is arbitrary —
48
+ // so filter on lastStatus and compare start times instead of trusting
49
+ // position. `excludeUnhealthy` proves service recovery (diagnose); exec
50
+ // keeps unhealthy-but-running tasks (often the debug target).
51
+ export function pickNewestRunningTask(tasks = [], { excludeUnhealthy = false } = {}) {
52
+ let newest = null;
53
+ let newestStart = 0;
54
+ for (const task of tasks || []) {
55
+ if (task?.lastStatus !== 'RUNNING') continue;
56
+ if (excludeUnhealthy && task?.healthStatus === 'UNHEALTHY') continue;
57
+ const started = taskStartedAtMs(task);
58
+ if (!newest || started > newestStart) {
59
+ newest = task;
60
+ newestStart = started;
61
+ }
62
+ }
63
+ return newest;
64
+ }
65
+
36
66
  // Container preference shared by the interactive commands: the expected
37
67
  // name first, then the first RUNNING container, then the first entry.
38
68
  // Works for both live tasks and task-definition `containerDefinitions`
@@ -3,12 +3,30 @@ import path from 'path';
3
3
  import { confirm, isCancel } from '@clack/prompts';
4
4
  import { ensureStateBucketExists } from './aws.js';
5
5
  import { parseStateBucketBackend } from './terraform-metadata.js';
6
+ import { refuseIfNonInteractive } from './command.js';
6
7
 
7
8
  // Asks whether to recreate a missing state bucket and resume
8
9
  // provisioning. Returns true when approved. Has no side effects
9
10
  // besides the prompt itself — callers own telemetry and the resume.
10
- export async function promptStateBucketRecovery({ autoApprove = false } = {}) {
11
+ //
12
+ // Non-interactive gate: apply is the sole caller, so the gate lives
13
+ // here (apply context) instead of at a call site. Pass `options` (plus
14
+ // `projectName` for telemetry) and a headless run without approval
15
+ // flags refuses loudly with APPLY_NON_INTERACTIVE — returning the
16
+ // failure result for the caller to propagate — instead of abandoning
17
+ // the prompt. Callers answering boolean keep working unchanged.
18
+ export async function promptStateBucketRecovery({ autoApprove = false, options = null, projectName = null } = {}) {
11
19
  if (autoApprove === true || autoApprove === 'true') return true;
20
+ if (options !== null && options !== undefined) {
21
+ const refused = await refuseIfNonInteractive(options, {
22
+ message: `\n✖ apply needs approval to recreate the missing state bucket and resume provisioning.`,
23
+ hint: ' Re-run with --auto-approve to recover non-interactively.\n',
24
+ event: 'infrastructure_applied',
25
+ telemetry: { projectName },
26
+ errorCode: 'APPLY_NON_INTERACTIVE',
27
+ });
28
+ if (refused) return refused;
29
+ }
12
30
  const shouldRecreate = await confirm({
13
31
  message: 'Do you want to automatically recreate the state bucket and resume provisioning?\nPrevious state is unrecoverable — if infrastructure still exists (bucket deleted out-of-band), apply will try to recreate it.',
14
32
  initialValue: true,
@@ -8,7 +8,7 @@ import { atomicWriteFileSync } from './atomic-write.js';
8
8
  import { withProjectLock } from './file-lock.js';
9
9
  import { ensureGitignoreRules, GITIGNORE_RULE_GRADA_DIR } from './gitignore.js';
10
10
  import { trackEvent, trackSuccess, flushTelemetry } from '../core/telemetry.js';
11
- import { resolveProjectName, resolveWorkspaceSuffix, resolveCluster, resolveService, resolveCwd, readResourceSuffix } from './resolvers.js';
11
+ import { resolveProjectName, resolveWorkspaceSuffix, resolveCluster, resolveService, resolveCwd, readResourceSuffix, resolveHeadless } from './resolvers.js';
12
12
  import { resolveDbIdentifier, resolveDbClusterIdentifier } from './rds.js';
13
13
 
14
14
  export const SLEEP_STATE_DIRNAME = '.grada';
@@ -238,7 +238,7 @@ export async function guardSleepingEnv({
238
238
  await flushTelemetry();
239
239
  return { proceed: true, entry };
240
240
  }
241
- if (shouldAutoApprove(opts)) {
241
+ if (shouldAutoApprove(opts) || resolveHeadless(opts)) {
242
242
  return {
243
243
  proceed: false,
244
244
  result: await failCommand({
@@ -6,6 +6,7 @@ import { SLEEP_STATE_DIRNAME } from './sleep-state.js';
6
6
  import { atomicWriteFileSync } from './atomic-write.js';
7
7
  import { normalizeOptions } from './args.js';
8
8
  import { failCommand, shouldAutoApprove } from './command.js';
9
+ import { resolveHeadless } from './resolvers.js';
9
10
  import { trackEvent } from '../core/telemetry.js';
10
11
 
11
12
  // Shared home for grada provenance metadata: stripping managed markers
@@ -157,7 +158,7 @@ export async function requireManagedTree({
157
158
  }
158
159
  if (opts.force === true || opts.force === 'true') return { proceed: true, ejected: which };
159
160
 
160
- if (shouldAutoApprove(opts)) {
161
+ if (shouldAutoApprove(opts) || resolveHeadless(opts)) {
161
162
  trackEvent('managed_tree_refused', { projectName: project, command });
162
163
  return {
163
164
  proceed: false,