grada-run 0.45.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -102,6 +102,7 @@ The interactive wizard will analyze your codebase, detect your framework, estima
102
102
  | [`status`](./apps/docs/src/content/docs/cli/status.md) | Health dashboard with live Golden Signals, auto-`diagnose` on degradation, `--json` for scripts, and `--watch` for live repaint. |
103
103
  | [`rollback`](./apps/docs/src/content/docs/cli/rollback.md) | Returns the live service to a previous task revision, with live progress (ECS only). |
104
104
  | [`exec`](./apps/docs/src/content/docs/cli/exec.md) | Opens a shell in a running container via Session Manager (ECS only). |
105
+ | [`run`](./apps/docs/src/content/docs/cli/run.md) | Runs a one-off command in a fresh, disposable container inside the VPC — backfills, seeders, admin scripts — with live logs (ECS only). |
105
106
  | [`db connect`](./apps/docs/src/content/docs/cli/db.md) | Opens a `localhost` tunnel to your private database (PostgreSQL, MySQL, or Aurora). |
106
107
  | [`db migrate`](./apps/docs/src/content/docs/cli/db.md) | Runs migrations inside the VPC (auto-detected) or installs the CI pre-deploy gate. |
107
108
  | [`db enable-vector`](./apps/docs/src/content/docs/cli/db.md) | Enables `pgvector` for AI embeddings with a one-off VPC task. |
package/bin/cli.js CHANGED
@@ -12,6 +12,7 @@ import { syncAi } from '../src/commands/sync-ai.js';
12
12
  import { runLogs, parseLogsArgs } from '../src/commands/logs.js';
13
13
  import { runStatus, parseStatusArgs } from '../src/commands/status.js';
14
14
  import { runExec, parseExecArgs } from '../src/commands/exec.js';
15
+ import { runRun, parseRunArgs } from '../src/commands/run.js';
15
16
  import { runDb } from '../src/commands/db.js';
16
17
  import { runRollback, parseRollbackArgs } from '../src/commands/rollback.js';
17
18
  import { runGc, parseGcArgs } from '../src/commands/gc.js';
@@ -42,6 +43,7 @@ const HELP_TEXT = [
42
43
  ' status Service health dashboard (--region, --json, --watch, --workspace)',
43
44
  ' rollback [rev] Roll back ECS service to a previous task revision (ECS only — Lambda uses image tags)',
44
45
  ' exec Open an interactive shell in a running container (--cluster, --service, --container, --command, --region, --workspace)',
46
+ ' run Run a one-off command in an ephemeral ECS task (--cmd, --task-def, --timeout, --workspace)',
45
47
  ' db connect Open a secure local tunnel to your database (--port, --show-credentials, --workspace, --region)',
46
48
  ' db enable-vector Enable the pgvector extension via a one-off ECS task (--task-def, --timeout)',
47
49
  ' db import Import a SQL dump into your database (--file, --from, --yes)',
@@ -172,6 +174,8 @@ if (wantsVersion) {
172
174
  runCommand(runRollback({ ...parseRollbackArgs(commandArgs), ...(isHeadless ? { isHeadless: true } : {}) }));
173
175
  } else if (positionalArgs[0] === 'exec') {
174
176
  runCommand(runExec({ ...parseExecArgs(commandArgs), ...(isHeadless ? { isHeadless: true } : {}) }));
177
+ } else if (positionalArgs[0] === 'run') {
178
+ runCommand(runRun({ ...parseRunArgs(commandArgs), ...(isHeadless ? { isHeadless: true } : {}) }));
175
179
  } else if (positionalArgs[0] === 'db') {
176
180
  runCommand(runDb(commandArgs, { ...(isHeadless ? { isHeadless: true } : {}) }));
177
181
  } else if (positionalArgs[0] === 'gc') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grada-run",
3
- "version": "0.45.0",
3
+ "version": "0.46.0",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -16,9 +16,8 @@ import {
16
16
  resolveCwd,
17
17
  } from '../../utils/resolvers.js';
18
18
  import { resolveContainer } from '../../utils/ecs.js';
19
- import { runEphemeralEcsTask } from '../../utils/ecs-runner.js';
19
+ import { runEphemeralEcsTask, buildRunnerCommand } from '../../utils/ecs-runner.js';
20
20
  import { parseTimeoutSeconds } from '../../utils/system.js';
21
- import { buildMigrationCommand } from './migrate.js';
22
21
  import fsSync from 'fs';
23
22
  import path from 'path';
24
23
 
@@ -235,7 +234,7 @@ async function runDbEnableVectorMain(input = {}) {
235
234
  service,
236
235
  containerName,
237
236
  taskDef: (typeof options.taskDef === 'string' && options.taskDef.trim()) ? options.taskDef.trim() : null,
238
- command: (containerDef) => buildMigrationCommand(vectorScript, containerDef),
237
+ command: (containerDef) => buildRunnerCommand(vectorScript, containerDef),
239
238
  startedBy: 'grada-db-enable-vector',
240
239
  logGroupName,
241
240
  timeoutMs,
@@ -2,8 +2,8 @@ import { ECSClient } from '@aws-sdk/client-ecs';
2
2
  import { CloudWatchLogsClient } from '@aws-sdk/client-cloudwatch-logs';
3
3
  import color from 'picocolors';
4
4
  import { intro, outro, spinner, text, isCancel } from '@clack/prompts';
5
- import { trackEvent, trackSuccess, setActiveCommandName, resetActiveCommandName, getCliVersion } from '../../core/telemetry.js';
6
- import { failCommand, failAwsError, failNamedContainerMissing, trackAwsFailure, failProjectNotInitialized, refuseUnknownFlags } from '../../utils/command.js';
5
+ import { trackSuccess, setActiveCommandName, resetActiveCommandName, getCliVersion } from '../../core/telemetry.js';
6
+ import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized, refuseUnknownFlags } from '../../utils/command.js';
7
7
  import { parseFlags, normalizeOptions, normalizeArgv } from '../../utils/args.js';
8
8
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../../utils/aws.js';
9
9
  import {
@@ -15,13 +15,11 @@ import {
15
15
  resolveAppName,
16
16
  resolveHeadless,
17
17
  resolveCwd,
18
- readFileSafe,
19
18
  readTerraformComputeTarget,
20
19
  } from '../../utils/resolvers.js';
21
- import { detectMigrationCommand, isNpmShimCommand, dockerfileStripsNpmShims, ormMappedHintSegment } from '../../utils/detector.js';
20
+ import { detectMigrationCommand } from '../../utils/detector.js';
22
21
  import { resolveContainer } from '../../utils/ecs.js';
23
- import { runEphemeralEcsTask } from '../../utils/ecs-runner.js';
24
- import { parseTimeoutSeconds } from '../../utils/system.js';
22
+ import { runEphemeralEcsTask, buildRunnerCommand, parseRunnerTimeout, guardNpmStrippedRunner, reportRunnerOutcome } from '../../utils/ecs-runner.js';
25
23
  import { atomicWriteFile } from '../../utils/atomic-write.js';
26
24
  import { pinnedActionUse } from '../../data/action-pins.js';
27
25
  import fsSync from 'fs';
@@ -181,69 +179,9 @@ export function injectPreviewMigrationGate(workflowContent, { cmd, cliVersion }
181
179
  });
182
180
  }
183
181
 
184
- // Sniffs the URL scheme from discrete credentials. Explicit values win;
185
- // when DB_ENGINE/DB_PORT are secrets-sourced (valueFrom, values unknown
186
- // to the CLI) the reference text is sniffed for engine/port hints
187
- // instead (BUG-171). Indeterminate stays postgresql (back-compat).
188
- function sniffMigrationScheme(entries, values) {
189
- const engine = values.get('DB_ENGINE');
190
- if (typeof engine === 'string' && engine !== '') {
191
- return /mysql|maria/i.test(engine) ? 'mysql' : 'postgresql';
192
- }
193
- const port = values.get('DB_PORT');
194
- if (typeof port === 'string' && port !== '') {
195
- return port === '3306' ? 'mysql' : 'postgresql';
196
- }
197
- const refs = entries.map((entry) => entry?.valueFrom).filter((ref) => typeof ref === 'string').join('\n');
198
- if (/mysql|maria|3306/i.test(refs)) return 'mysql';
199
- return 'postgresql';
200
- }
201
-
202
- // Runtime userinfo encoder for the synthesized URL (BUG-139): node sees
203
- // only shell references, never the values, so the encoding ladder ships
204
- // inside the script — node (encodeURIComponent) → sed (the URL-breaking
205
- // subset: %, ?, #, @, :, /) → warned raw. Quoting alone cannot save a
206
- // `?` or `#` in the password: the URL parser (not the shell) is what
207
- // breaks, so the shell refs must be encoded, not quoted.
208
- function buildEncodedUrlExport({ scheme, defaultPort, defaultName }) {
209
- const nodeEncode = `node -e 'var s="${scheme}",a=process.argv.slice(1);console.log(s+"://"+encodeURIComponent(a[0])+":"+encodeURIComponent(a[1])+"@"+a[2]+":"+a[3]+"/"+a[4])' "$_u" "$_p" "$_h" "$_o" "$_n"`;
210
- const sedEncode = `printf '${scheme}://%s:%s@%s:%s/%s' "$(_grada_enc "$_u")" "$(_grada_enc "$_p")" "$_h" "$_o" "$_n"`;
211
- const rawEncode = `printf '${scheme}://%s:%s@%s:%s/%s' "$_u" "$_p" "$_h" "$_o" "$_n"`;
212
- return `_grada_db_url() { _u="\${DB_USER}"; _p="\${DB_PASSWORD}"; _h="\${DB_HOST}"; _o="\${DB_PORT:-${defaultPort}}"; _n="\${DB_NAME:-${defaultName}}"; `
213
- + `if command -v node >/dev/null 2>&1; then ${nodeEncode}; `
214
- + `elif command -v sed >/dev/null 2>&1; then _grada_enc() { printf '%s' "$1" | sed -e 's/%/%25/g' -e 's/?/%3F/g' -e 's/#/%23/g' -e 's/@/%40/g' -e 's/:/%3A/g' -e 's|/|%2F|g'; }; ${sedEncode}; `
215
- + `else echo "grada: warning: DATABASE_URL built without userinfo encoding (no node or sed in image)" >&2; ${rawEncode}; fi; }; `
216
- + `if [ -z "\${DATABASE_URL:-}" ]; then export DATABASE_URL="$(_grada_db_url)"; fi`;
217
- }
218
-
219
- // Builds the container override command for the migration task. When the
220
- // task definition provides discrete `DB_*` credentials but no
221
- // `DATABASE_URL`, the command exports a runtime-synthesized URL (from the
222
- // container's own environment, so secrets never cross the RunTask API
223
- // call) before running the user's migration command. Pure and unit-tested.
224
- export function buildMigrationCommand(resolvedCmd, containerDef) {
225
- const cmd = String(resolvedCmd ?? '');
226
- const environment = Array.isArray(containerDef?.environment) ? containerDef.environment : [];
227
- const secrets = Array.isArray(containerDef?.secrets) ? containerDef.secrets : [];
228
- const entries = [...environment, ...secrets];
229
- const names = new Set(entries.map((entry) => entry?.name));
230
- if (names.has('DATABASE_URL')) return ['sh', '-c', cmd];
231
- if (!names.has('DB_HOST') || !names.has('DB_USER') || !names.has('DB_PASSWORD')) {
232
- return ['sh', '-c', cmd];
233
- }
234
- const values = new Map(entries.map((entry) => [entry?.name, entry?.value]));
235
- const scheme = sniffMigrationScheme(entries, values);
236
- // RDS/Aurora enforces `rds.force_ssl = 1` by default: require TLS for
237
- // synthesized postgres URLs so libpq-based migrations never fail on a
238
- // plaintext connection (MySQL clients ignore PGSSLMODE; leave them alone).
239
- const tlsPrefix = scheme === 'postgresql' ? 'export PGSSLMODE="${PGSSLMODE:-require}"; ' : '';
240
- const urlExport = buildEncodedUrlExport({
241
- scheme,
242
- defaultPort: scheme === 'mysql' ? '3306' : '5432',
243
- defaultName: scheme === 'mysql' ? 'mysql' : 'postgres',
244
- });
245
- return ['sh', '-c', `${tlsPrefix}${urlExport}; ${cmd}`];
246
- }
182
+ // Back-compat alias: the synthesis logic now lives in ecs-runner.js as
183
+ // buildRunnerCommand (shared by migrate, enable-vector, and run).
184
+ export { buildRunnerCommand as buildMigrationCommand };
247
185
 
248
186
  // Programmatic entry wrapper: stamps cli_command for telemetry on every
249
187
  // invocation path, including direct imports that bypass bin/cli.js and MCP.
@@ -297,17 +235,13 @@ async function runDbMigrateMain(input = {}) {
297
235
  });
298
236
  }
299
237
 
300
- const timeoutSeconds = parseTimeoutSeconds(options.timeout, DEFAULT_MIGRATE_TIMEOUT_SECONDS);
301
- if (timeoutSeconds === null) {
302
- return failCommand({
303
- message: `\n✖ Invalid --timeout "${options.timeout}". Use a positive number of seconds (default ${DEFAULT_MIGRATE_TIMEOUT_SECONDS}).\n`,
304
- event: 'db_migrate_run',
305
- telemetry: { projectName },
306
- errorCode: 'INVALID_TIMEOUT',
307
- reason: 'invalid-timeout',
308
- resultExtra: { cluster, service, region },
309
- });
310
- }
238
+ const parsedTimeout = await parseRunnerTimeout(options.timeout, DEFAULT_MIGRATE_TIMEOUT_SECONDS, {
239
+ event: 'db_migrate_run',
240
+ telemetry: { projectName },
241
+ resultExtra: { cluster, service, region },
242
+ });
243
+ if (typeof parsedTimeout !== 'number') return parsedTimeout;
244
+ const timeoutSeconds = parsedTimeout;
311
245
 
312
246
  // 1. Resolve the migration command (shared by live runs and --setup-ci).
313
247
  let resolvedCmd = null;
@@ -345,27 +279,14 @@ async function runDbMigrateMain(input = {}) {
345
279
  }
346
280
  }
347
281
 
348
- // 1b. Stripped-runner guard: Grada's node-family images
349
- // remove npm/npx/yarn from the runner stage, so an npm-shim command
350
- // is a guaranteed `command not found` inside the task. Fail fast
351
- // headless; warn loudly (and proceed) interactively. Fail-open when
352
- // no Dockerfile is present — nothing to prove breakage against.
353
- if (isNpmShimCommand(resolvedCmd) && dockerfileStripsNpmShims(readFileSafe(path.join(cwd, 'Dockerfile')))) {
354
- const ormHint = ormMappedHintSegment(cwd, '--cmd ');
355
- if (headless) {
356
- return failCommand({
357
- message: `\n✖ Refusing to run "${resolvedCmd}": your Dockerfile strips npm/npx from the runner image, so this command would fail with "command not found" inside the task.\n`,
358
- hint: ` Bundle a framework-compiled runner instead and re-run with an explicit node-based command, e.g. --cmd "node ./dist/migrate.cjs". Ensure your Dockerfile builds the bundle and copies it into the runner image${ormHint}.\n`,
359
- event: 'db_migrate_run',
360
- telemetry: { projectName, cmd_source: cmdSource, ci_setup: setupCi, error_code: 'NPM_CMD_STRIPPED_RUNNER' },
361
- errorCode: 'NPM_CMD_STRIPPED_RUNNER',
362
- reason: 'npm-cmd-stripped-runner',
363
- resultExtra: { cluster, service, region },
364
- });
365
- }
366
- console.log(color.yellow(`⚠️ "${resolvedCmd}" starts with npm/npx but your Dockerfile strips those binaries from the runner image — this will fail with "command not found" 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}`));
367
- trackEvent('npm_cmd_stripped_runner', { projectName, cmd_source: cmdSource, ci_setup: setupCi });
368
- }
282
+ // 1b. Stripped-runner guard (shared with `run`).
283
+ const strippedRefusal = await guardNpmStrippedRunner({
284
+ resolvedCmd, cwd, headless,
285
+ event: 'db_migrate_run',
286
+ telemetry: { projectName, cmd_source: cmdSource, ci_setup: setupCi },
287
+ resultExtra: { cluster, service, region },
288
+ });
289
+ if (strippedRefusal) return strippedRefusal;
369
290
 
370
291
  // 2. --setup-ci: patch the workflow file, no AWS calls.
371
292
  if (setupCi) {
@@ -456,7 +377,7 @@ async function runDbMigrateMain(input = {}) {
456
377
  service,
457
378
  containerName,
458
379
  taskDef: (typeof options.taskDef === 'string' && options.taskDef.trim()) ? options.taskDef.trim() : null,
459
- command: (containerDef) => buildMigrationCommand(resolvedCmd, containerDef),
380
+ command: (containerDef) => buildRunnerCommand(resolvedCmd, containerDef),
460
381
  startedBy: 'grada-db-migrate',
461
382
  logGroupName,
462
383
  timeoutMs,
@@ -468,103 +389,20 @@ async function runDbMigrateMain(input = {}) {
468
389
  taskNoun: 'migration',
469
390
  });
470
391
 
471
- if (!outcome.ok && outcome.code === 'ECS_SERVICE_NOT_FOUND') {
472
- s.stop(color.yellow('Service not found.'));
473
- return failCommand({
474
- print: () => {
475
- console.log(`\n The ECS service ${color.cyan(service)} does not exist or is inactive.`);
476
- console.log(` Run ${color.green('npx grada-run apply')} to provision your infrastructure.\n`);
477
- },
478
- event: 'db_migrate_run',
479
- telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
480
- errorCode: 'ECS_SERVICE_NOT_FOUND',
481
- reason: 'ecs-service-not-found',
482
- resultExtra: { cluster, service, region },
483
- });
484
- }
485
-
486
- if (!outcome.ok && outcome.code === 'NO_VPC_CONFIG') {
487
- s.stop(color.red('Service has no VPC configuration.'));
488
- return failCommand({
489
- message: `\n✖ The ECS service ${color.cyan(service)} has no VPC network configuration, so the migration task cannot be placed.\n`,
490
- event: 'db_migrate_run',
491
- telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
492
- errorCode: 'RUN_TASK_FAILED',
493
- reason: 'run-task-failed',
494
- resultExtra: { cluster, service, region },
495
- });
496
- }
497
-
498
- if (!outcome.ok && outcome.code === 'CONTAINER_NOT_FOUND') {
499
- s.stop(color.red('Container not found.'));
500
- return failCommand({
501
- message: `\n✖ Container "${containerName}" does not exist in task definition "${outcome.targetTaskDef}".\n`,
502
- hint: `Override with --container <name>. Available: ${outcome.available.join(', ') || 'none'}\n`,
503
- event: 'db_migrate_run',
504
- telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
505
- errorCode: 'CONTAINER_NOT_FOUND',
506
- reason: 'container-not-found',
507
- resultExtra: { cluster, service, region },
508
- });
509
- }
510
-
511
- if (!outcome.ok && outcome.code === 'RUN_TASK_FAILED') {
512
- s.stop(color.red('Failed to start migration task.'));
513
- return failCommand({
514
- message: `\n✖ ECS could not start the migration task: ${outcome.reason}.\n`,
515
- event: 'db_migrate_run',
516
- telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
517
- errorCode: 'RUN_TASK_FAILED',
518
- reason: 'run-task-failed',
519
- resultExtra: { cluster, service, region },
520
- });
521
- }
522
- if (!outcome.ok && outcome.code === 'NAMED_CONTAINER_MISSING') {
523
- return failNamedContainerMissing({
524
- spinner: s, outcome, cluster, service, region,
525
- event: 'db_migrate_run',
526
- telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
527
- noun: 'Migration',
528
- });
529
- }
530
- if (!outcome.ok && outcome.code === 'TIMEOUT') {
531
- try { s.stop(color.yellow('Migration timed out.')); } catch { /* already stopped */ }
532
- return failCommand({
533
- message: `\n✖ Migration timed out after ${timeoutSeconds}s. The task was stopped (best-effort); increase --timeout and retry.\n`,
534
- event: 'db_migrate_run',
535
- telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
536
- errorCode: 'MIGRATION_TIMEOUT',
537
- reason: 'migration-timeout',
538
- resultExtra: { cluster, service, region, taskArn: outcome.taskArn },
539
- });
540
- }
541
-
542
- const exitCode = outcome.exitCode;
543
- const stoppedReason = outcome.stoppedReason;
544
- if (exitCode === 0) {
545
- // Owner pairs its own start/stop: the runner usually stops
546
- // first (idempotent no-op then), but success must never
547
- // depend on a callee for the spinner lifecycle (BUG-202).
548
- try { s.stop(color.green('Migration succeeded.')); } catch { /* already stopped */ }
549
- console.log(color.green('\n✅ Migration succeeded.'));
550
- await trackSuccess('db_migrate_run', { projectName, cmd_source: cmdSource, ci_setup: false });
551
- outro(color.green('Done.'));
552
- return { ok: true, success: true, exitCode: 0, taskArn: outcome.taskArn };
553
- }
554
- const propagated = (typeof exitCode === 'number' && exitCode > 0) ? exitCode : 1;
555
- // The ECS stopped reason is the only diagnosis PostHog gets for a
556
- // failed task (exit codes alone can't distinguish image-pull from
557
- // command-not-found from migration errors) — stamp it.
558
- const failureDetail = `Migration failed with exit code ${exitCode ?? 'unknown'}: ${stoppedReason}`;
559
- return failCommand({
560
- message: `\n✖ ${failureDetail}.\n`,
392
+ // Outcome mapping shared with `run` (labels parameterize the copy).
393
+ return reportRunnerOutcome({
394
+ outcome, spinner: s,
561
395
  event: 'db_migrate_run',
562
396
  telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
563
- errorCode: 'MIGRATION_TASK_FAILED',
564
- extra: { exit_code: exitCode ?? -1, error_message: failureDetail },
565
- reason: 'migration-task-failed',
566
- resultExtra: { cluster, service, region, taskArn: outcome.taskArn },
567
- exitCode: propagated,
397
+ cluster, service, region,
398
+ containerName,
399
+ label: 'Migration',
400
+ taskPhrase: 'migration task',
401
+ timeoutSeconds,
402
+ timeoutCode: 'MIGRATION_TIMEOUT',
403
+ timeoutReason: 'migration-timeout',
404
+ taskFailedCode: 'MIGRATION_TASK_FAILED',
405
+ taskFailedReason: 'migration-task-failed',
568
406
  });
569
407
  } catch (error) {
570
408
  if (isAuthError(error)) {
@@ -0,0 +1,232 @@
1
+ import { ECSClient } from '@aws-sdk/client-ecs';
2
+ import { CloudWatchLogsClient } from '@aws-sdk/client-cloudwatch-logs';
3
+ import color from 'picocolors';
4
+ import { intro, outro, spinner, text, isCancel } from '@clack/prompts';
5
+ import { setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
6
+ import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized, refuseUnknownFlags } from '../utils/command.js';
7
+ import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
8
+ import { isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
9
+ import {
10
+ resolveRegion,
11
+ resolveProjectName,
12
+ resolveCluster,
13
+ resolveService,
14
+ resolveLogGroup,
15
+ resolveAppName,
16
+ resolveHeadless,
17
+ resolveCwd,
18
+ guardComputeTarget,
19
+ } from '../utils/resolvers.js';
20
+ import { resolveContainer } from '../utils/ecs.js';
21
+ import { runEphemeralEcsTask, buildRunnerCommand, parseRunnerTimeout, guardNpmStrippedRunner, reportRunnerOutcome } from '../utils/ecs-runner.js';
22
+
23
+ export const DEFAULT_RUN_TIMEOUT_SECONDS = 600;
24
+ export const DEFAULT_POLL_INTERVAL_MS = 2000;
25
+ export const DEFAULT_FLUSH_MAX_POLLS = 6;
26
+ export const DEFAULT_FLUSH_INTERVAL_MS = 1000;
27
+
28
+ export const RUN_NODE_EXAMPLE = 'node ./dist/backfill.cjs';
29
+
30
+ const LAMBDA_TARGET_HINT = ' Ephemeral Fargate tasks need an ECS service — remote execution is not supported on Lambda targets yet.\n';
31
+ const STATIC_TARGET_HINT = ' Static sites provision no compute — there is no container to execute against.\n';
32
+
33
+ export function parseRunArgs(argv = []) {
34
+ const args = normalizeArgv(argv);
35
+ if (args[0] === 'run') args.shift();
36
+ const { options, rest, unknown } = parseFlags(args, {
37
+ string: [
38
+ { name: 'cmd', key: 'cmd', greedy: true },
39
+ { name: 'task-def', key: 'taskDef' },
40
+ { name: 'timeout', key: 'timeout' },
41
+ { name: 'project-name', key: 'projectName' },
42
+ { name: 'region', key: 'region' },
43
+ { name: 'workspace', key: 'workspace' },
44
+ { name: 'cluster', key: 'cluster' },
45
+ { name: 'service', key: 'service' },
46
+ { name: 'container', key: 'container' },
47
+ ],
48
+ boolean: ['headless'],
49
+ });
50
+ const positionals = rest.filter((arg) => typeof arg === 'string' && !arg.startsWith('-'));
51
+ if (positionals.length > 0) options.unexpectedPositionals = positionals;
52
+ if (unknown.length > 0) options.unknownFlags = unknown;
53
+ return options;
54
+ }
55
+
56
+ // Programmatic entry wrapper: stamps cli_command for telemetry on every
57
+ // invocation path, including direct imports that bypass bin/cli.js and MCP.
58
+ export async function runRun(input = {}) {
59
+ setActiveCommandName('run');
60
+ try {
61
+ return await runRunMain(input);
62
+ } finally {
63
+ resetActiveCommandName();
64
+ }
65
+ }
66
+
67
+ async function runRunMain(input = {}) {
68
+ const options = normalizeOptions(input);
69
+ const unknownRefusal = await refuseUnknownFlags(options, { command: 'run', event: 'run_run' });
70
+ if (unknownRefusal) return unknownRefusal;
71
+ let cwd;
72
+ let region;
73
+ let projectName;
74
+ let cluster;
75
+ let service;
76
+ let containerName;
77
+ let logGroupName;
78
+ try {
79
+ cwd = resolveCwd(options);
80
+ region = resolveRegion(options, cwd);
81
+ projectName = resolveProjectName(options, cwd);
82
+ const appName = resolveAppName(projectName, options.workspace, cwd);
83
+ const namespacedOptions = { ...options, projectName: appName };
84
+ cluster = resolveCluster(namespacedOptions, cwd);
85
+ service = resolveService(namespacedOptions, cwd);
86
+ containerName = resolveContainer(namespacedOptions, cwd);
87
+ logGroupName = resolveLogGroup(namespacedOptions, cwd);
88
+ } catch {
89
+ return failProjectNotInitialized({ event: 'run_run' });
90
+ }
91
+ const headless = resolveHeadless(options);
92
+
93
+ intro(color.bgCyan(color.black(' grada run 🏃 ')));
94
+
95
+ if (Array.isArray(options.unexpectedPositionals) && options.unexpectedPositionals.length > 0) {
96
+ return failCommand({
97
+ message: `\n✖ Unexpected argument "${options.unexpectedPositionals[0]}". Wrap multi-word --cmd values in quotes: --cmd "${options.unexpectedPositionals.join(' ')}".\n`,
98
+ event: 'run_run',
99
+ telemetry: { projectName },
100
+ errorCode: 'UNEXPECTED_POSITIONAL_ARGS',
101
+ reason: 'unexpected-positional-args',
102
+ resultExtra: { cluster, service, region },
103
+ });
104
+ }
105
+
106
+ // One-off tasks run on ECS Fargate — refuse other targets before
107
+ // prompting or constructing AWS clients.
108
+ const targetGuard = guardComputeTarget({ cwd, command: 'Remote command execution', supported: ['ecs'] });
109
+ if (targetGuard) {
110
+ return failCommand({
111
+ message: targetGuard.message,
112
+ hint: targetGuard.actual === 'lambda' ? LAMBDA_TARGET_HINT : STATIC_TARGET_HINT,
113
+ event: 'run_run',
114
+ telemetry: { projectName },
115
+ errorCode: targetGuard.errorCode,
116
+ reason: targetGuard.reason,
117
+ resultExtra: { cluster, service, region },
118
+ });
119
+ }
120
+
121
+ const parsedTimeout = await parseRunnerTimeout(options.timeout, DEFAULT_RUN_TIMEOUT_SECONDS, {
122
+ event: 'run_run',
123
+ telemetry: { projectName },
124
+ resultExtra: { cluster, service, region },
125
+ });
126
+ if (typeof parsedTimeout !== 'number') return parsedTimeout;
127
+ const timeoutSeconds = parsedTimeout;
128
+
129
+ // Resolve the command: explicit --cmd, else an interactive prompt.
130
+ // Generic commands cannot be auto-detected like migrations, so
131
+ // headless runs without --cmd fail closed.
132
+ let resolvedCmd = null;
133
+ let cmdSource = null;
134
+ if (typeof options.cmd === 'string' && options.cmd.trim()) {
135
+ resolvedCmd = options.cmd.trim();
136
+ cmdSource = 'explicit';
137
+ } else if (!headless) {
138
+ const answer = await text({
139
+ message: 'Command to run inside the VPC:',
140
+ placeholder: 'e.g. node ./dist/backfill.cjs',
141
+ });
142
+ if (isCancel(answer) || typeof answer !== 'string' || !answer.trim()) {
143
+ outro(color.yellow('Run cancelled.'));
144
+ return { ok: false, reason: 'cancelled', cluster, service, region };
145
+ }
146
+ resolvedCmd = answer.trim();
147
+ cmdSource = 'prompted';
148
+ } else {
149
+ return failCommand({
150
+ message: '\n✖ No command to run. Pass --cmd "<command>" (e.g. --cmd "node ./dist/backfill.cjs").\n',
151
+ event: 'run_run',
152
+ telemetry: { projectName, cmd_source: 'none' },
153
+ errorCode: 'MISSING_RUN_CMD',
154
+ reason: 'missing-run-cmd',
155
+ resultExtra: { cluster, service, region },
156
+ });
157
+ }
158
+
159
+ // Stripped-runner guard (shared with `db migrate`).
160
+ const strippedRefusal = await guardNpmStrippedRunner({
161
+ resolvedCmd, cwd, headless,
162
+ event: 'run_run',
163
+ telemetry: { projectName, cmd_source: cmdSource },
164
+ resultExtra: { cluster, service, region },
165
+ nodeExample: RUN_NODE_EXAMPLE,
166
+ });
167
+ if (strippedRefusal) return strippedRefusal;
168
+
169
+ // Live run: discover the service and launch a one-off task.
170
+ const ecsClient = resolveClient(options.ecsClient, ECSClient, { region });
171
+ const logsClient = resolveClient(options.logsClient ?? options.cloudwatchClient, CloudWatchLogsClient, { region });
172
+ const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
173
+ const maxFlushPolls = options.maxFlushPolls ?? DEFAULT_FLUSH_MAX_POLLS;
174
+ const flushIntervalMs = options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;
175
+ const timeoutMs = options.timeoutMs ?? timeoutSeconds * 1000;
176
+
177
+ const s = spinner();
178
+ s.start('Starting one-off task...');
179
+
180
+ try {
181
+ const outcome = await runEphemeralEcsTask({
182
+ ecsClient,
183
+ logsClient,
184
+ cluster,
185
+ service,
186
+ containerName,
187
+ taskDef: (typeof options.taskDef === 'string' && options.taskDef.trim()) ? options.taskDef.trim() : null,
188
+ command: (containerDef) => buildRunnerCommand(resolvedCmd, containerDef),
189
+ startedBy: 'grada-run',
190
+ logGroupName,
191
+ timeoutMs,
192
+ timeoutSeconds,
193
+ pollIntervalMs,
194
+ maxFlushPolls,
195
+ flushIntervalMs,
196
+ spinner: s,
197
+ taskNoun: 'one-off',
198
+ });
199
+
200
+ // Outcome mapping shared with `db migrate` (labels parameterize the copy).
201
+ return reportRunnerOutcome({
202
+ outcome, spinner: s,
203
+ event: 'run_run',
204
+ telemetry: { projectName, cmd_source: cmdSource },
205
+ cluster, service, region,
206
+ containerName,
207
+ label: 'Task',
208
+ taskPhrase: 'one-off task',
209
+ timeoutSeconds,
210
+ timeoutCode: 'RUN_TIMEOUT',
211
+ timeoutReason: 'run-timeout',
212
+ taskFailedCode: 'RUN_COMMAND_FAILED',
213
+ taskFailedReason: 'run-command-failed',
214
+ });
215
+ } catch (error) {
216
+ if (isAuthError(error)) {
217
+ await trackAwsFailure('run_run', error, { projectName, cmd_source: cmdSource });
218
+ handleAuthErrorBranch(error, s, options);
219
+ return { ok: false, reason: 'error', cluster, service, region };
220
+ }
221
+ try { s.stop(color.red('❌ Run failed.')); } catch { /* spinner already stopped */ }
222
+ return failAwsError({
223
+ event: 'run_run',
224
+ error,
225
+ telemetry: { projectName, cmd_source: cmdSource },
226
+ reason: 'error',
227
+ resultExtra: { cluster, service, region },
228
+ });
229
+ }
230
+ }
231
+
232
+ export default runRun;
@@ -6,10 +6,16 @@ import {
6
6
  } from '@aws-sdk/client-ecs';
7
7
  import { FilterLogEventsCommand, GetLogEventsCommand } from '@aws-sdk/client-cloudwatch-logs';
8
8
  import color from 'picocolors';
9
+ import path from 'path';
10
+ import { outro } from '@clack/prompts';
9
11
  import { fetchActiveService, pickRuntimeContainer } from './ecs.js';
10
- import { sleep, pollUntil } from './system.js';
12
+ import { sleep, pollUntil, parseTimeoutSeconds } from './system.js';
11
13
  import { truncateSpinnerText } from './spinner-text.js';
12
14
  import { isNotFoundError, buildLogStreamName } from '../commands/logs.js';
15
+ import { failCommand, failNamedContainerMissing } from './command.js';
16
+ import { trackEvent, trackSuccess } from '../core/telemetry.js';
17
+ import { readFileSafe } from './resolvers.js';
18
+ import { isNpmShimCommand, dockerfileStripsNpmShims, ormMappedHintSegment } from './detector.js';
13
19
 
14
20
  export const DEFAULT_RUNNER_POLL_INTERVAL_MS = 2000;
15
21
  export const DEFAULT_RUNNER_FLUSH_MAX_POLLS = 6;
@@ -301,3 +307,229 @@ export async function runEphemeralEcsTask({
301
307
  const stoppedReason = match.reason || finalTask?.stoppedReason || 'unknown';
302
308
  return { ok: true, taskArn, exitCode, stoppedReason };
303
309
  }
310
+
311
+ // Sniffs the URL scheme from discrete credentials. Explicit values win;
312
+ // when DB_ENGINE/DB_PORT are secrets-sourced (valueFrom, values unknown
313
+ // to the CLI) the reference text is sniffed for engine/port hints
314
+ // instead (BUG-171). Indeterminate stays postgresql (back-compat).
315
+ function sniffRunnerScheme(entries, values) {
316
+ const engine = values.get('DB_ENGINE');
317
+ if (typeof engine === 'string' && engine !== '') {
318
+ return /mysql|maria/i.test(engine) ? 'mysql' : 'postgresql';
319
+ }
320
+ const port = values.get('DB_PORT');
321
+ if (typeof port === 'string' && port !== '') {
322
+ return port === '3306' ? 'mysql' : 'postgresql';
323
+ }
324
+ const refs = entries.map((entry) => entry?.valueFrom).filter((ref) => typeof ref === 'string').join('\n');
325
+ if (/mysql|maria|3306/i.test(refs)) return 'mysql';
326
+ return 'postgresql';
327
+ }
328
+
329
+ // Runtime userinfo encoder for the synthesized URL (BUG-139): node sees
330
+ // only shell references, never the values, so the encoding ladder ships
331
+ // inside the script — node (encodeURIComponent) → sed (the URL-breaking
332
+ // subset: %, ?, #, @, :, /) → warned raw. Quoting alone cannot save a
333
+ // `?` or `#` in the password: the URL parser (not the shell) is what
334
+ // breaks, so the shell refs must be encoded, not quoted.
335
+ function buildEncodedUrlExport({ scheme, defaultPort, defaultName }) {
336
+ const nodeEncode = `node -e 'var s="${scheme}",a=process.argv.slice(1);console.log(s+"://"+encodeURIComponent(a[0])+":"+encodeURIComponent(a[1])+"@"+a[2]+":"+a[3]+"/"+a[4])' "$_u" "$_p" "$_h" "$_o" "$_n"`;
337
+ const sedEncode = `printf '${scheme}://%s:%s@%s:%s/%s' "$(_grada_enc "$_u")" "$(_grada_enc "$_p")" "$_h" "$_o" "$_n"`;
338
+ const rawEncode = `printf '${scheme}://%s:%s@%s:%s/%s' "$_u" "$_p" "$_h" "$_o" "$_n"`;
339
+ return `_grada_db_url() { _u="\${DB_USER}"; _p="\${DB_PASSWORD}"; _h="\${DB_HOST}"; _o="\${DB_PORT:-${defaultPort}}"; _n="\${DB_NAME:-${defaultName}}"; `
340
+ + `if command -v node >/dev/null 2>&1; then ${nodeEncode}; `
341
+ + `elif command -v sed >/dev/null 2>&1; then _grada_enc() { printf '%s' "$1" | sed -e 's/%/%25/g' -e 's/?/%3F/g' -e 's/#/%23/g' -e 's/@/%40/g' -e 's/:/%3A/g' -e 's|/|%2F|g'; }; ${sedEncode}; `
342
+ + `else echo "grada: warning: DATABASE_URL built without userinfo encoding (no node or sed in image)" >&2; ${rawEncode}; fi; }; `
343
+ + `if [ -z "\${DATABASE_URL:-}" ]; then export DATABASE_URL="$(_grada_db_url)"; fi`;
344
+ }
345
+
346
+ // Builds the container override command for an ephemeral runner task. When
347
+ // the task definition provides discrete `DB_*` credentials but no
348
+ // `DATABASE_URL`, the command exports a runtime-synthesized URL (from the
349
+ // container's own environment, so secrets never cross the RunTask API
350
+ // call) before running the user's command. Pure and unit-tested.
351
+ export function buildRunnerCommand(resolvedCmd, containerDef) {
352
+ const cmd = String(resolvedCmd ?? '');
353
+ const environment = Array.isArray(containerDef?.environment) ? containerDef.environment : [];
354
+ const secrets = Array.isArray(containerDef?.secrets) ? containerDef.secrets : [];
355
+ const entries = [...environment, ...secrets];
356
+ const names = new Set(entries.map((entry) => entry?.name));
357
+ if (names.has('DATABASE_URL')) return ['sh', '-c', cmd];
358
+ if (!names.has('DB_HOST') || !names.has('DB_USER') || !names.has('DB_PASSWORD')) {
359
+ return ['sh', '-c', cmd];
360
+ }
361
+ const values = new Map(entries.map((entry) => [entry?.name, entry?.value]));
362
+ const scheme = sniffRunnerScheme(entries, values);
363
+ // RDS/Aurora enforces `rds.force_ssl = 1` by default: require TLS for
364
+ // synthesized postgres URLs so libpq-based migrations never fail on a
365
+ // plaintext connection (MySQL clients ignore PGSSLMODE; leave them alone).
366
+ const tlsPrefix = scheme === 'postgresql' ? 'export PGSSLMODE="${PGSSLMODE:-require}"; ' : '';
367
+ const urlExport = buildEncodedUrlExport({
368
+ scheme,
369
+ defaultPort: scheme === 'mysql' ? '3306' : '5432',
370
+ defaultName: scheme === 'mysql' ? 'mysql' : 'postgres',
371
+ });
372
+ return ['sh', '-c', `${tlsPrefix}${urlExport}; ${cmd}`];
373
+ }
374
+
375
+ // Validates `--timeout` for ephemeral-runner commands (`db migrate`,
376
+ // `run`): returns the seconds on success, or the failCommand result
377
+ // (printed, tracked, and exited) when invalid. Callers branch on
378
+ // `typeof result !== 'number'`.
379
+ export async function parseRunnerTimeout(timeoutRaw, defaultSeconds, { event, telemetry = {}, resultExtra = {} } = {}) {
380
+ const timeoutSeconds = parseTimeoutSeconds(timeoutRaw, defaultSeconds);
381
+ if (timeoutSeconds !== null) return timeoutSeconds;
382
+ return failCommand({
383
+ message: `\n✖ Invalid --timeout "${timeoutRaw}". Use a positive number of seconds (default ${defaultSeconds}).\n`,
384
+ event,
385
+ telemetry,
386
+ errorCode: 'INVALID_TIMEOUT',
387
+ reason: 'invalid-timeout',
388
+ resultExtra,
389
+ });
390
+ }
391
+
392
+ // Stripped-runner guard for ephemeral-runner commands: Grada's
393
+ // node-family images remove npm/npx/yarn from the runner stage, so an
394
+ // npm-shim command is a guaranteed `command not found` inside the task.
395
+ // Fail fast headless; warn loudly (and proceed) interactively. Fail-open
396
+ // when no Dockerfile is present — nothing to prove breakage against.
397
+ // Returns null to proceed, or the failCommand result when refusing.
398
+ export async function guardNpmStrippedRunner({
399
+ resolvedCmd, cwd, headless, event, telemetry = {}, resultExtra = {},
400
+ nodeExample = 'node ./dist/migrate.cjs',
401
+ }) {
402
+ if (!isNpmShimCommand(resolvedCmd) || !dockerfileStripsNpmShims(readFileSafe(path.join(cwd, 'Dockerfile')))) {
403
+ return null;
404
+ }
405
+ const ormHint = ormMappedHintSegment(cwd, '--cmd ');
406
+ if (headless) {
407
+ return failCommand({
408
+ message: `\n✖ Refusing to run "${resolvedCmd}": your Dockerfile strips npm/npx from the runner image, so this command would fail with "command not found" inside the task.\n`,
409
+ hint: ` Bundle a framework-compiled runner instead and re-run with an explicit node-based command, e.g. --cmd "${nodeExample}". Ensure your Dockerfile builds the bundle and copies it into the runner image${ormHint}.\n`,
410
+ event,
411
+ telemetry: { ...telemetry, error_code: 'NPM_CMD_STRIPPED_RUNNER' },
412
+ errorCode: 'NPM_CMD_STRIPPED_RUNNER',
413
+ reason: 'npm-cmd-stripped-runner',
414
+ resultExtra,
415
+ });
416
+ }
417
+ console.log(color.yellow(`⚠️ "${resolvedCmd}" starts with npm/npx but your Dockerfile strips those binaries from the runner image — this will fail with "command not found" unless you switch to a node-based command (e.g. "${nodeExample}"). Ensure your Dockerfile builds the bundle and copies it into the runner image.${ormHint}`));
418
+ trackEvent('npm_cmd_stripped_runner', { ...telemetry });
419
+ return null;
420
+ }
421
+
422
+ // Maps a runEphemeralEcsTask outcome to the caller's terminal result:
423
+ // stops the spinner with command-specific wording, prints, tracks, and
424
+ // exits via failCommand — or records success and returns the success
425
+ // object. `label` names the finished unit ("Migration succeeded."),
426
+ // `taskPhrase` names the placed unit ("the migration task cannot be
427
+ // placed"). Callers return this result directly.
428
+ export async function reportRunnerOutcome({
429
+ outcome, spinner: s, event, telemetry = {},
430
+ cluster, service, region,
431
+ containerName, label, taskPhrase,
432
+ timeoutSeconds, timeoutCode, timeoutReason,
433
+ taskFailedCode, taskFailedReason,
434
+ }) {
435
+ const resultExtra = { cluster, service, region };
436
+
437
+ if (!outcome.ok && outcome.code === 'ECS_SERVICE_NOT_FOUND') {
438
+ s.stop(color.yellow('Service not found.'));
439
+ return failCommand({
440
+ print: () => {
441
+ console.log(`\n The ECS service ${color.cyan(service)} does not exist or is inactive.`);
442
+ console.log(` Run ${color.green('npx grada-run apply')} to provision your infrastructure.\n`);
443
+ },
444
+ event,
445
+ telemetry,
446
+ errorCode: 'ECS_SERVICE_NOT_FOUND',
447
+ reason: 'ecs-service-not-found',
448
+ resultExtra,
449
+ });
450
+ }
451
+
452
+ if (!outcome.ok && outcome.code === 'NO_VPC_CONFIG') {
453
+ s.stop(color.red('Service has no VPC configuration.'));
454
+ return failCommand({
455
+ message: `\n✖ The ECS service ${color.cyan(service)} has no VPC network configuration, so the ${taskPhrase} cannot be placed.\n`,
456
+ event,
457
+ telemetry,
458
+ errorCode: 'RUN_TASK_FAILED',
459
+ reason: 'run-task-failed',
460
+ resultExtra,
461
+ });
462
+ }
463
+
464
+ if (!outcome.ok && outcome.code === 'CONTAINER_NOT_FOUND') {
465
+ s.stop(color.red('Container not found.'));
466
+ return failCommand({
467
+ message: `\n✖ Container "${containerName}" does not exist in task definition "${outcome.targetTaskDef}".\n`,
468
+ hint: `Override with --container <name>. Available: ${outcome.available.join(', ') || 'none'}\n`,
469
+ event,
470
+ telemetry,
471
+ errorCode: 'CONTAINER_NOT_FOUND',
472
+ reason: 'container-not-found',
473
+ resultExtra,
474
+ });
475
+ }
476
+
477
+ if (!outcome.ok && outcome.code === 'RUN_TASK_FAILED') {
478
+ s.stop(color.red(`Failed to start ${taskPhrase}.`));
479
+ return failCommand({
480
+ message: `\n✖ ECS could not start the ${taskPhrase}: ${outcome.reason}.\n`,
481
+ event,
482
+ telemetry,
483
+ errorCode: 'RUN_TASK_FAILED',
484
+ reason: 'run-task-failed',
485
+ resultExtra,
486
+ });
487
+ }
488
+ if (!outcome.ok && outcome.code === 'NAMED_CONTAINER_MISSING') {
489
+ return failNamedContainerMissing({
490
+ spinner: s, outcome, cluster, service, region,
491
+ event,
492
+ telemetry,
493
+ noun: label,
494
+ });
495
+ }
496
+ if (!outcome.ok && outcome.code === 'TIMEOUT') {
497
+ try { s.stop(color.yellow(`${label} timed out.`)); } catch { /* already stopped */ }
498
+ return failCommand({
499
+ message: `\n✖ ${label} timed out after ${timeoutSeconds}s. The task was stopped (best-effort); increase --timeout and retry.\n`,
500
+ event,
501
+ telemetry,
502
+ errorCode: timeoutCode,
503
+ reason: timeoutReason,
504
+ resultExtra: { ...resultExtra, taskArn: outcome.taskArn },
505
+ });
506
+ }
507
+
508
+ const exitCode = outcome.exitCode;
509
+ const stoppedReason = outcome.stoppedReason;
510
+ if (exitCode === 0) {
511
+ // Owner pairs its own start/stop: the runner usually stops
512
+ // first (idempotent no-op then), but success must never
513
+ // depend on a callee for the spinner lifecycle (BUG-202).
514
+ try { s.stop(color.green(`${label} succeeded.`)); } catch { /* already stopped */ }
515
+ console.log(color.green(`\n✅ ${label} succeeded.`));
516
+ await trackSuccess(event, { ...telemetry });
517
+ outro(color.green('Done.'));
518
+ return { ok: true, success: true, exitCode: 0, taskArn: outcome.taskArn };
519
+ }
520
+ const propagated = (typeof exitCode === 'number' && exitCode > 0) ? exitCode : 1;
521
+ // The ECS stopped reason is the only diagnosis PostHog gets for a
522
+ // failed task (exit codes alone can't distinguish image-pull from
523
+ // command-not-found from task errors) — stamp it.
524
+ const failureDetail = `${label} failed with exit code ${exitCode ?? 'unknown'}: ${stoppedReason}`;
525
+ return failCommand({
526
+ message: `\n✖ ${failureDetail}.\n`,
527
+ event,
528
+ telemetry,
529
+ errorCode: taskFailedCode,
530
+ extra: { exit_code: exitCode ?? -1, error_message: failureDetail },
531
+ reason: taskFailedReason,
532
+ resultExtra: { ...resultExtra, taskArn: outcome.taskArn },
533
+ exitCode: propagated,
534
+ });
535
+ }