grada-run 0.44.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)',
@@ -131,7 +133,7 @@ function runCommand(promise) {
131
133
  // Help wins over every subcommand: no flow — destructive or otherwise —
132
134
  // may execute from a help invocation. `db` keeps its own usage path
133
135
  // inside runDb (db usage for `db --help` and every `db <leaf> --help`,
134
- // exit 0; bare `db` still reports its missing subcommand).
136
+ // exit 0; bare `db` prints usage the same untracked way).
135
137
  const wantsHelp = positionalArgs[0] === 'help' || rawArgs.includes('--help') || rawArgs.includes('-h');
136
138
  // Version wins over every subcommand like help does — but unlike help it
137
139
  // needs no `db` exemption: the version is global, identical everywhere.
@@ -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.44.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"
@@ -15,6 +15,12 @@ export const DEFAULT_BACKUP_POLL_INTERVAL_MS = 5000;
15
15
 
16
16
  const SNAPSHOT_NOT_FOUND_NAMES = new Set(['DBSnapshotNotFound', 'DBSnapshotNotFoundFault']);
17
17
  const CLUSTER_SNAPSHOT_NOT_FOUND_NAMES = new Set(['DBClusterSnapshotNotFound', 'DBClusterSnapshotNotFoundFault']);
18
+ const SNAPSHOT_ALREADY_EXISTS_NAMES = new Set([
19
+ 'DBSnapshotAlreadyExists',
20
+ 'DBSnapshotAlreadyExistsFault',
21
+ 'DBClusterSnapshotAlreadyExists',
22
+ 'DBClusterSnapshotAlreadyExistsFault',
23
+ ]);
18
24
  // Snapshot states that never become available: polling past them only
19
25
  // wastes the timeout and misreports.
20
26
  const TERMINAL_SNAPSHOT_STATUSES = new Set(['failed', 'deleted', 'deleting']);
@@ -142,25 +148,43 @@ async function runDbBackupMain(input = {}) {
142
148
  { Key: 'ManagedBy', Value: 'grada' },
143
149
  { Key: 'Project', Value: projectName },
144
150
  ];
145
- if (isCluster) {
146
- await rdsClient.send(new CreateDBClusterSnapshotCommand({
147
- DBClusterIdentifier: target.id,
148
- DBClusterSnapshotIdentifier: snapshotId,
149
- Tags: snapshotTags,
150
- }));
151
- } else {
152
- await rdsClient.send(new CreateDBSnapshotCommand({
153
- DBInstanceIdentifier: target.id,
154
- DBSnapshotIdentifier: snapshotId,
155
- Tags: snapshotTags,
156
- }));
151
+ // An existing id is success, not failure: CI retries and re-runs of
152
+ // the same migration must not fail just because the snapshot step
153
+ // already ran. The wait below then resolves its actual state
154
+ // (available, still creating, or failed) the same as a fresh create.
155
+ let reusedExisting = false;
156
+ try {
157
+ if (isCluster) {
158
+ await rdsClient.send(new CreateDBClusterSnapshotCommand({
159
+ DBClusterIdentifier: target.id,
160
+ DBClusterSnapshotIdentifier: snapshotId,
161
+ Tags: snapshotTags,
162
+ }));
163
+ } else {
164
+ await rdsClient.send(new CreateDBSnapshotCommand({
165
+ DBInstanceIdentifier: target.id,
166
+ DBSnapshotIdentifier: snapshotId,
167
+ Tags: snapshotTags,
168
+ }));
169
+ }
170
+ } catch (error) {
171
+ if (error && SNAPSHOT_ALREADY_EXISTS_NAMES.has(error.name)) {
172
+ reusedExisting = true;
173
+ } else {
174
+ throw error;
175
+ }
157
176
  }
158
177
 
159
178
  if (noWait) {
160
- s.stop(color.green('Snapshot creation started.'));
161
- console.log(`\n Snapshot ${color.cyan(snapshotId)} is being created (status: creating).`);
179
+ if (reusedExisting) {
180
+ s.stop(color.green('Snapshot already exists.'));
181
+ console.log(`\n Snapshot ${color.cyan(snapshotId)} already exists — reusing it.`);
182
+ } else {
183
+ s.stop(color.green('Snapshot creation started.'));
184
+ console.log(`\n Snapshot ${color.cyan(snapshotId)} is being created (status: creating).`);
185
+ }
162
186
  console.log(color.dim(` Restore it later with: npx grada-run db restore ${snapshotId}\n`));
163
- await trackSuccess('db_backup_run', { projectName, waited: false, db_kind: target.kind });
187
+ await trackSuccess('db_backup_run', { projectName, waited: false, db_kind: target.kind, reused_existing: reusedExisting });
164
188
  outro(color.green('Done.'));
165
189
  return { ok: true, snapshotId, status: 'creating' };
166
190
  }
@@ -243,7 +267,7 @@ async function runDbBackupMain(input = {}) {
243
267
  s.stop(color.green('Snapshot available.'));
244
268
  console.log(`\n Snapshot ${color.cyan(snapshotId)} is ready.`);
245
269
  console.log(color.dim(` Restore it with: npx grada-run db restore ${snapshotId}\n`));
246
- await trackSuccess('db_backup_run', { projectName, waited: true, db_kind: target.kind });
270
+ await trackSuccess('db_backup_run', { projectName, waited: true, db_kind: target.kind, reused_existing: reusedExisting });
247
271
  outro(color.green('Done.'));
248
272
  return { ok: true, snapshotId, status: 'available' };
249
273
  } catch (error) {
@@ -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';
@@ -86,7 +84,7 @@ export function quoteShellArg(value) {
86
84
  return `'${String(value).replace(/'/g, `'\\''`)}'`;
87
85
  }
88
86
 
89
- function renderGateBlock({ includeSetupNode, stepName, runLine }) {
87
+ function renderGateBlock({ includeSetupNode, steps }) {
90
88
  const lines = [` ${GATE_START_MARKER}`];
91
89
  if (includeSetupNode) {
92
90
  lines.push(
@@ -97,16 +95,18 @@ function renderGateBlock({ includeSetupNode, stepName, runLine }) {
97
95
  ''
98
96
  );
99
97
  }
100
- lines.push(
101
- ` - name: ${stepName}`,
102
- // Gates run AWS calls: honor the credential-skip outcome like
103
- // every other post-assume step (BUG-138). Neutral on deploy
104
- // (a failed assume fails the run before any gate runs).
105
- ` if: steps.aws-creds.outcome == 'success'`,
106
- ' run: |',
107
- ` ${runLine}`,
108
- ` ${GATE_END_MARKER}`
109
- );
98
+ for (const { stepName, runLine } of steps) {
99
+ lines.push(
100
+ ` - name: ${stepName}`,
101
+ // Gates run AWS calls: honor the credential-skip outcome like
102
+ // every other post-assume step (BUG-138). Neutral on deploy
103
+ // (a failed assume fails the run before any gate runs).
104
+ ` if: steps.aws-creds.outcome == 'success'`,
105
+ ' run: |',
106
+ ` ${runLine}`
107
+ );
108
+ }
109
+ lines.push(` ${GATE_END_MARKER}`);
110
110
  return `${lines.join('\n')}\n`;
111
111
  }
112
112
 
@@ -132,10 +132,10 @@ export function buildRunnerInvocation(cliVersion) {
132
132
 
133
133
  // Shared injection core: strips any previous gate, renders the block, and
134
134
  // splices it before the anchor step. Returns null without the anchor.
135
- function injectGateBlock(content, { runLine, stepName, anchor }) {
135
+ function injectGateBlock(content, { steps, anchor }) {
136
136
  const base = stripPreviousGateBlock(String(content ?? ''));
137
137
  const includeSetupNode = !base.includes('actions/setup-node');
138
- const block = renderGateBlock({ includeSetupNode, stepName, runLine });
138
+ const block = renderGateBlock({ includeSetupNode, steps });
139
139
  const anchorIdx = base.indexOf(anchor);
140
140
  if (anchorIdx === -1) return null;
141
141
  const insertAt = base.lastIndexOf('\n', anchorIdx) + 1;
@@ -147,9 +147,18 @@ function injectGateBlock(content, { runLine, stepName, anchor }) {
147
147
  // anchor step is present. Pure and unit-tested.
148
148
  export function injectMigrationGate(workflowContent, { cmd, cliVersion } = {}) {
149
149
  const taskDefRef = '${{ steps.register-task-def.outputs.task-arn }}';
150
+ const runner = buildRunnerInvocation(cliVersion);
150
151
  return injectGateBlock(workflowContent, {
151
- stepName: 'Pre-Deploy Database Migration',
152
- runLine: `${buildRunnerInvocation(cliVersion)} db migrate --cmd ${quoteShellArg(cmd)} --task-def "${taskDefRef}" --headless`,
152
+ steps: [
153
+ {
154
+ stepName: 'Take pre-migration database snapshot',
155
+ runLine: `${runner} db backup --id "pre-deploy-\${{ github.sha }}" --headless`,
156
+ },
157
+ {
158
+ stepName: 'Pre-Deploy Database Migration',
159
+ runLine: `${runner} db migrate --cmd ${quoteShellArg(cmd)} --task-def "${taskDefRef}" --headless`,
160
+ },
161
+ ],
153
162
  anchor: '- name: Force ECS deployment',
154
163
  });
155
164
  }
@@ -160,75 +169,19 @@ export function injectMigrationGate(workflowContent, { cmd, cliVersion } = {}) {
160
169
  // service itself via --workspace. Returns null without the anchor.
161
170
  export function injectPreviewMigrationGate(workflowContent, { cmd, cliVersion } = {}) {
162
171
  return injectGateBlock(workflowContent, {
163
- stepName: 'Preview Database Migration',
164
- runLine: `${buildRunnerInvocation(cliVersion)} db migrate --cmd ${quoteShellArg(cmd)} --workspace "\${{ env.WORKSPACE }}" --headless`,
172
+ steps: [
173
+ {
174
+ stepName: 'Preview Database Migration',
175
+ runLine: `${buildRunnerInvocation(cliVersion)} db migrate --cmd ${quoteShellArg(cmd)} --workspace "\${{ env.WORKSPACE }}" --headless`,
176
+ },
177
+ ],
165
178
  anchor: '- name: Comment PR',
166
179
  });
167
180
  }
168
181
 
169
- // Sniffs the URL scheme from discrete credentials. Explicit values win;
170
- // when DB_ENGINE/DB_PORT are secrets-sourced (valueFrom, values unknown
171
- // to the CLI) the reference text is sniffed for engine/port hints
172
- // instead (BUG-171). Indeterminate stays postgresql (back-compat).
173
- function sniffMigrationScheme(entries, values) {
174
- const engine = values.get('DB_ENGINE');
175
- if (typeof engine === 'string' && engine !== '') {
176
- return /mysql|maria/i.test(engine) ? 'mysql' : 'postgresql';
177
- }
178
- const port = values.get('DB_PORT');
179
- if (typeof port === 'string' && port !== '') {
180
- return port === '3306' ? 'mysql' : 'postgresql';
181
- }
182
- const refs = entries.map((entry) => entry?.valueFrom).filter((ref) => typeof ref === 'string').join('\n');
183
- if (/mysql|maria|3306/i.test(refs)) return 'mysql';
184
- return 'postgresql';
185
- }
186
-
187
- // Runtime userinfo encoder for the synthesized URL (BUG-139): node sees
188
- // only shell references, never the values, so the encoding ladder ships
189
- // inside the script — node (encodeURIComponent) → sed (the URL-breaking
190
- // subset: %, ?, #, @, :, /) → warned raw. Quoting alone cannot save a
191
- // `?` or `#` in the password: the URL parser (not the shell) is what
192
- // breaks, so the shell refs must be encoded, not quoted.
193
- function buildEncodedUrlExport({ scheme, defaultPort, defaultName }) {
194
- 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"`;
195
- const sedEncode = `printf '${scheme}://%s:%s@%s:%s/%s' "$(_grada_enc "$_u")" "$(_grada_enc "$_p")" "$_h" "$_o" "$_n"`;
196
- const rawEncode = `printf '${scheme}://%s:%s@%s:%s/%s' "$_u" "$_p" "$_h" "$_o" "$_n"`;
197
- return `_grada_db_url() { _u="\${DB_USER}"; _p="\${DB_PASSWORD}"; _h="\${DB_HOST}"; _o="\${DB_PORT:-${defaultPort}}"; _n="\${DB_NAME:-${defaultName}}"; `
198
- + `if command -v node >/dev/null 2>&1; then ${nodeEncode}; `
199
- + `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}; `
200
- + `else echo "grada: warning: DATABASE_URL built without userinfo encoding (no node or sed in image)" >&2; ${rawEncode}; fi; }; `
201
- + `if [ -z "\${DATABASE_URL:-}" ]; then export DATABASE_URL="$(_grada_db_url)"; fi`;
202
- }
203
-
204
- // Builds the container override command for the migration task. When the
205
- // task definition provides discrete `DB_*` credentials but no
206
- // `DATABASE_URL`, the command exports a runtime-synthesized URL (from the
207
- // container's own environment, so secrets never cross the RunTask API
208
- // call) before running the user's migration command. Pure and unit-tested.
209
- export function buildMigrationCommand(resolvedCmd, containerDef) {
210
- const cmd = String(resolvedCmd ?? '');
211
- const environment = Array.isArray(containerDef?.environment) ? containerDef.environment : [];
212
- const secrets = Array.isArray(containerDef?.secrets) ? containerDef.secrets : [];
213
- const entries = [...environment, ...secrets];
214
- const names = new Set(entries.map((entry) => entry?.name));
215
- if (names.has('DATABASE_URL')) return ['sh', '-c', cmd];
216
- if (!names.has('DB_HOST') || !names.has('DB_USER') || !names.has('DB_PASSWORD')) {
217
- return ['sh', '-c', cmd];
218
- }
219
- const values = new Map(entries.map((entry) => [entry?.name, entry?.value]));
220
- const scheme = sniffMigrationScheme(entries, values);
221
- // RDS/Aurora enforces `rds.force_ssl = 1` by default: require TLS for
222
- // synthesized postgres URLs so libpq-based migrations never fail on a
223
- // plaintext connection (MySQL clients ignore PGSSLMODE; leave them alone).
224
- const tlsPrefix = scheme === 'postgresql' ? 'export PGSSLMODE="${PGSSLMODE:-require}"; ' : '';
225
- const urlExport = buildEncodedUrlExport({
226
- scheme,
227
- defaultPort: scheme === 'mysql' ? '3306' : '5432',
228
- defaultName: scheme === 'mysql' ? 'mysql' : 'postgres',
229
- });
230
- return ['sh', '-c', `${tlsPrefix}${urlExport}; ${cmd}`];
231
- }
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 };
232
185
 
233
186
  // Programmatic entry wrapper: stamps cli_command for telemetry on every
234
187
  // invocation path, including direct imports that bypass bin/cli.js and MCP.
@@ -282,17 +235,13 @@ async function runDbMigrateMain(input = {}) {
282
235
  });
283
236
  }
284
237
 
285
- const timeoutSeconds = parseTimeoutSeconds(options.timeout, DEFAULT_MIGRATE_TIMEOUT_SECONDS);
286
- if (timeoutSeconds === null) {
287
- return failCommand({
288
- message: `\n✖ Invalid --timeout "${options.timeout}". Use a positive number of seconds (default ${DEFAULT_MIGRATE_TIMEOUT_SECONDS}).\n`,
289
- event: 'db_migrate_run',
290
- telemetry: { projectName },
291
- errorCode: 'INVALID_TIMEOUT',
292
- reason: 'invalid-timeout',
293
- resultExtra: { cluster, service, region },
294
- });
295
- }
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;
296
245
 
297
246
  // 1. Resolve the migration command (shared by live runs and --setup-ci).
298
247
  let resolvedCmd = null;
@@ -330,27 +279,14 @@ async function runDbMigrateMain(input = {}) {
330
279
  }
331
280
  }
332
281
 
333
- // 1b. Stripped-runner guard: Grada's node-family images
334
- // remove npm/npx/yarn from the runner stage, so an npm-shim command
335
- // is a guaranteed `command not found` inside the task. Fail fast
336
- // headless; warn loudly (and proceed) interactively. Fail-open when
337
- // no Dockerfile is present — nothing to prove breakage against.
338
- if (isNpmShimCommand(resolvedCmd) && dockerfileStripsNpmShims(readFileSafe(path.join(cwd, 'Dockerfile')))) {
339
- const ormHint = ormMappedHintSegment(cwd, '--cmd ');
340
- if (headless) {
341
- return failCommand({
342
- 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`,
343
- 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`,
344
- event: 'db_migrate_run',
345
- telemetry: { projectName, cmd_source: cmdSource, ci_setup: setupCi, error_code: 'NPM_CMD_STRIPPED_RUNNER' },
346
- errorCode: 'NPM_CMD_STRIPPED_RUNNER',
347
- reason: 'npm-cmd-stripped-runner',
348
- resultExtra: { cluster, service, region },
349
- });
350
- }
351
- 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}`));
352
- trackEvent('npm_cmd_stripped_runner', { projectName, cmd_source: cmdSource, ci_setup: setupCi });
353
- }
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;
354
290
 
355
291
  // 2. --setup-ci: patch the workflow file, no AWS calls.
356
292
  if (setupCi) {
@@ -398,7 +334,7 @@ async function runDbMigrateMain(input = {}) {
398
334
  }
399
335
  await atomicWriteFile(workflowFile, updated, 'utf8');
400
336
  console.log(color.green('\n✅ Pre-deploy migration gate installed in .github/workflows/deploy.yml.'));
401
- console.log(color.dim(' Migrations now run against the new image revision before the ECS service updates.\n'));
337
+ console.log(color.dim(' Each deploy now snapshots the database, then runs migrations against the new image revision before the ECS service updates.\n'));
402
338
  if (readTerraformComputeTarget(cwd) === 'ecs') {
403
339
  const previewFile = path.join(cwd, '.github', 'workflows', 'preview.yml');
404
340
  let previewContent = null;
@@ -441,7 +377,7 @@ async function runDbMigrateMain(input = {}) {
441
377
  service,
442
378
  containerName,
443
379
  taskDef: (typeof options.taskDef === 'string' && options.taskDef.trim()) ? options.taskDef.trim() : null,
444
- command: (containerDef) => buildMigrationCommand(resolvedCmd, containerDef),
380
+ command: (containerDef) => buildRunnerCommand(resolvedCmd, containerDef),
445
381
  startedBy: 'grada-db-migrate',
446
382
  logGroupName,
447
383
  timeoutMs,
@@ -453,103 +389,20 @@ async function runDbMigrateMain(input = {}) {
453
389
  taskNoun: 'migration',
454
390
  });
455
391
 
456
- if (!outcome.ok && outcome.code === 'ECS_SERVICE_NOT_FOUND') {
457
- s.stop(color.yellow('Service not found.'));
458
- return failCommand({
459
- print: () => {
460
- console.log(`\n The ECS service ${color.cyan(service)} does not exist or is inactive.`);
461
- console.log(` Run ${color.green('npx grada-run apply')} to provision your infrastructure.\n`);
462
- },
463
- event: 'db_migrate_run',
464
- telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
465
- errorCode: 'ECS_SERVICE_NOT_FOUND',
466
- reason: 'ecs-service-not-found',
467
- resultExtra: { cluster, service, region },
468
- });
469
- }
470
-
471
- if (!outcome.ok && outcome.code === 'NO_VPC_CONFIG') {
472
- s.stop(color.red('Service has no VPC configuration.'));
473
- return failCommand({
474
- message: `\n✖ The ECS service ${color.cyan(service)} has no VPC network configuration, so the migration task cannot be placed.\n`,
475
- event: 'db_migrate_run',
476
- telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
477
- errorCode: 'RUN_TASK_FAILED',
478
- reason: 'run-task-failed',
479
- resultExtra: { cluster, service, region },
480
- });
481
- }
482
-
483
- if (!outcome.ok && outcome.code === 'CONTAINER_NOT_FOUND') {
484
- s.stop(color.red('Container not found.'));
485
- return failCommand({
486
- message: `\n✖ Container "${containerName}" does not exist in task definition "${outcome.targetTaskDef}".\n`,
487
- hint: `Override with --container <name>. Available: ${outcome.available.join(', ') || 'none'}\n`,
488
- event: 'db_migrate_run',
489
- telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
490
- errorCode: 'CONTAINER_NOT_FOUND',
491
- reason: 'container-not-found',
492
- resultExtra: { cluster, service, region },
493
- });
494
- }
495
-
496
- if (!outcome.ok && outcome.code === 'RUN_TASK_FAILED') {
497
- s.stop(color.red('Failed to start migration task.'));
498
- return failCommand({
499
- message: `\n✖ ECS could not start the migration task: ${outcome.reason}.\n`,
500
- event: 'db_migrate_run',
501
- telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
502
- errorCode: 'RUN_TASK_FAILED',
503
- reason: 'run-task-failed',
504
- resultExtra: { cluster, service, region },
505
- });
506
- }
507
- if (!outcome.ok && outcome.code === 'NAMED_CONTAINER_MISSING') {
508
- return failNamedContainerMissing({
509
- spinner: s, outcome, cluster, service, region,
510
- event: 'db_migrate_run',
511
- telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
512
- noun: 'Migration',
513
- });
514
- }
515
- if (!outcome.ok && outcome.code === 'TIMEOUT') {
516
- try { s.stop(color.yellow('Migration timed out.')); } catch { /* already stopped */ }
517
- return failCommand({
518
- message: `\n✖ Migration timed out after ${timeoutSeconds}s. The task was stopped (best-effort); increase --timeout and retry.\n`,
519
- event: 'db_migrate_run',
520
- telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
521
- errorCode: 'MIGRATION_TIMEOUT',
522
- reason: 'migration-timeout',
523
- resultExtra: { cluster, service, region, taskArn: outcome.taskArn },
524
- });
525
- }
526
-
527
- const exitCode = outcome.exitCode;
528
- const stoppedReason = outcome.stoppedReason;
529
- if (exitCode === 0) {
530
- // Owner pairs its own start/stop: the runner usually stops
531
- // first (idempotent no-op then), but success must never
532
- // depend on a callee for the spinner lifecycle (BUG-202).
533
- try { s.stop(color.green('Migration succeeded.')); } catch { /* already stopped */ }
534
- console.log(color.green('\n✅ Migration succeeded.'));
535
- await trackSuccess('db_migrate_run', { projectName, cmd_source: cmdSource, ci_setup: false });
536
- outro(color.green('Done.'));
537
- return { ok: true, success: true, exitCode: 0, taskArn: outcome.taskArn };
538
- }
539
- const propagated = (typeof exitCode === 'number' && exitCode > 0) ? exitCode : 1;
540
- // The ECS stopped reason is the only diagnosis PostHog gets for a
541
- // failed task (exit codes alone can't distinguish image-pull from
542
- // command-not-found from migration errors) — stamp it.
543
- const failureDetail = `Migration failed with exit code ${exitCode ?? 'unknown'}: ${stoppedReason}`;
544
- return failCommand({
545
- message: `\n✖ ${failureDetail}.\n`,
392
+ // Outcome mapping shared with `run` (labels parameterize the copy).
393
+ return reportRunnerOutcome({
394
+ outcome, spinner: s,
546
395
  event: 'db_migrate_run',
547
396
  telemetry: { projectName, cmd_source: cmdSource, ci_setup: false },
548
- errorCode: 'MIGRATION_TASK_FAILED',
549
- extra: { exit_code: exitCode ?? -1, error_message: failureDetail },
550
- reason: 'migration-task-failed',
551
- resultExtra: { cluster, service, region, taskArn: outcome.taskArn },
552
- 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',
553
406
  });
554
407
  } catch (error) {
555
408
  if (isAuthError(error)) {
@@ -114,13 +114,20 @@ async function runDbMain(argv = [], extraOptions = {}) {
114
114
  return runDbImport({ ...parseDbImportArgs(argv), ...extra });
115
115
  }
116
116
 
117
+ if (subcommand === undefined) {
118
+ // Bare invocation is help-seeking, not an error: usage + exit
119
+ // 0, untracked like --help (keeps probe noise out of error
120
+ // telemetry).
121
+ console.log(color.yellow('\n⚠ Missing db subcommand.'));
122
+ console.log('');
123
+ printDbUsage();
124
+ console.log('');
125
+ return { ok: true };
126
+ }
127
+
117
128
  return failCommand({
118
129
  print: () => {
119
- if (subcommand === undefined) {
120
- console.log(color.yellow('\n⚠ Missing db subcommand.'));
121
- } else {
122
- console.log(color.red(`\n✖ Unknown db subcommand "${subcommand}".`));
123
- }
130
+ console.log(color.red(`\n✖ Unknown db subcommand "${subcommand}".`));
124
131
  console.log('');
125
132
  printDbUsage();
126
133
  console.log('');
@@ -386,24 +386,28 @@ async function runDomainMain(input = {}) {
386
386
  intro(color.bgCyan(color.black(' grada domain 🌐 ')));
387
387
 
388
388
  if (!DOMAIN_SUBCOMMANDS.includes(subcommand)) {
389
- // Closed enum only — never echo the raw user token into telemetry.
390
- const telemetrySubcommand = typeof options.subcommand === 'string' && options.subcommand.trim() !== ''
391
- ? 'unknown'
392
- : 'none';
389
+ // Blank input trims to '' rather than undefined — same missing
390
+ // case the old 'none' telemetry bucket covered.
391
+ if (subcommand === undefined || subcommand === '') {
392
+ // Bare invocation is help-seeking, not an error: usage + exit
393
+ // 0, untracked like --help (keeps probe noise out of error
394
+ // telemetry).
395
+ console.log(color.yellow('\n⚠ Missing domain subcommand.'));
396
+ console.log('');
397
+ printDomainUsage();
398
+ console.log('');
399
+ return { ok: true };
400
+ }
393
401
  return failCommand({
394
402
  noExit,
395
403
  print: () => {
396
- if (subcommand === undefined) {
397
- console.log(color.yellow('\n⚠ Missing domain subcommand.'));
398
- } else {
399
- console.log(color.red(`\n✖ Unknown domain subcommand "${options.subcommand}".`));
400
- }
404
+ console.log(color.red(`\n✖ Unknown domain subcommand "${options.subcommand}".`));
401
405
  console.log('');
402
406
  printDomainUsage();
403
407
  console.log('');
404
408
  },
405
409
  event: 'domain_run',
406
- telemetry: { subcommand: telemetrySubcommand },
410
+ telemetry: { subcommand: 'unknown' },
407
411
  errorCode: 'UNKNOWN_DOMAIN_SUBCOMMAND',
408
412
  reason: 'unknown-domain-subcommand',
409
413
  });
@@ -903,7 +903,7 @@ async function mainStackMain(input = {}) {
903
903
  const gated = workflowContent ? injectMigrationGate(workflowContent, { cmd: migrationCmd, cliVersion: CLI_VERSION }) : null;
904
904
  if (gated) {
905
905
  atomicWriteFileSync(deployYmlPath, gated);
906
- console.log(color.green('✅ Wired the pre-deploy database migration gate into .github/workflows/deploy.yml'));
906
+ console.log(color.green('✅ Wired the pre-deploy database migration gate into .github/workflows/deploy.yml (snapshot first, then migrate)'));
907
907
  } else {
908
908
  log.warn(color.yellow('⚠️ Could not wire the migration gate: the deploy workflow anchor was not found.'));
909
909
  }
@@ -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
+ }