grada-run 0.41.4 → 0.42.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.
@@ -465,8 +465,12 @@ async function removeUntaggedImages({ ecrClient }, images) {
465
465
  }
466
466
  for (const [repositoryName, imageIds] of byRepo) {
467
467
  for (const batch of chunkArray(imageIds, ECR_BATCH_DELETE_LIMIT)) {
468
- await ecrClient.send(new BatchDeleteImageCommand({ repositoryName, imageIds: batch }));
469
- deletedImages += batch.length;
468
+ const resp = await ecrClient.send(new BatchDeleteImageCommand({ repositoryName, imageIds: batch }));
469
+ const failed = resp?.failures?.length ?? 0;
470
+ if (failed > 0) {
471
+ console.log(color.yellow(`⚠ ${failed} of ${batch.length} image(s) in ${repositoryName} failed to delete (${resp.failures[0]?.failureCode || 'unknown'}).`));
472
+ }
473
+ deletedImages += batch.length - failed;
470
474
  }
471
475
  }
472
476
  return deletedImages;
@@ -492,8 +496,22 @@ async function releaseUnattachedEips({ ec2Client }, eips) {
492
496
 
493
497
  export async function deleteDiscoveredResources(clients, discovered) {
494
498
  const summary = {};
499
+ const errors = [];
495
500
  for (const target of GC_TARGETS.filter((entry) => entry.scope === 'standard' && typeof entry.remove === 'function')) {
496
- summary[target.summary] = await target.remove(clients, discovered[target.field] || []);
501
+ try {
502
+ summary[target.summary] = await target.remove(clients, discovered[target.field] || []);
503
+ } catch (error) {
504
+ // One target's API failure must not strand the rest (BUG-105):
505
+ // record it, zero its count, and keep deleting.
506
+ errors.push({ target: target.summary, error });
507
+ summary[target.summary] = 0;
508
+ }
509
+ }
510
+ if (errors.length > 0) {
511
+ const failure = new Error(`gc deletion partially failed: ${errors.map(({ target, error }) => `${target} (${error?.message || error})`).join('; ')}`);
512
+ failure.partialSummary = summary;
513
+ failure.failures = errors;
514
+ throw failure;
497
515
  }
498
516
  return summary;
499
517
  }
@@ -718,7 +736,21 @@ async function runGcMain(input = {}) {
718
736
 
719
737
  const del = spinner();
720
738
  del.start('Deleting orphaned resources...');
721
- const summary = await deleteDiscoveredResources({ ecrClient, logsClient, ec2Client }, discovered);
739
+ let summary;
740
+ try {
741
+ summary = await deleteDiscoveredResources({ ecrClient, logsClient, ec2Client }, discovered);
742
+ } catch (error) {
743
+ del.stop(color.red('❌ Deletion partially failed.'));
744
+ const partial = (error && typeof error === 'object' && error.partialSummary) || {};
745
+ return failCommand({
746
+ message: `\n✖ ${error?.message || error}\n`,
747
+ hint: ' Completed targets stay deleted; fix the cause and re-run to finish the rest.\n',
748
+ event: 'gc_run',
749
+ telemetry: { projectName, error_code: 'GC_PARTIAL_DELETE_FAILED', ...partial },
750
+ reason: 'gc-partial-delete-failed',
751
+ resultExtra: { ...partial },
752
+ });
753
+ }
722
754
  del.stop('Deletion complete.');
723
755
 
724
756
  outro(color.green(`Deleted ${summary.deletedImages} image(s), ${summary.deletedLogGroups} log group(s), released ${summary.releasedEips} Elastic IP(s). ✅`));
@@ -82,15 +82,49 @@ export async function mainStack(input = {}) {
82
82
  }
83
83
  }
84
84
 
85
+ // Scoped classic claim shape: `repo:<owner>/<name>[:<suffix>]`. Owner and
86
+ // name exclude `@` (GitHub names cannot contain it), so immutable-format
87
+ // entries never match and pass through untouched.
88
+ const SCOPED_SUB_RE = /^repo:([^/@]+)\/([^/@:]+)(?::(.*))?$/;
89
+
90
+ // Builds the immutable-claim companion for a classic entry, or null when
91
+ // the entry is not classic-shaped (open trust, immutable entries, and
92
+ // anything exotic stay single).
93
+ export function immutableCompanion(classicSub) {
94
+ if (typeof classicSub !== 'string') return null;
95
+ const match = SCOPED_SUB_RE.exec(classicSub);
96
+ if (!match) return null;
97
+ const [, owner, name, rest] = match;
98
+ const suffix = rest === undefined ? '*' : rest;
99
+ return `repo:${owner}@*/${name}@*:${suffix}`;
100
+ }
101
+
102
+ // Renders the OIDC sub claim as an HCL value fragment: scoped trusts gain
103
+ // the immutable-claim companion (repos created after 2026-07-15 emit
104
+ // `repo:<owner>@<id>/<name>@<id>:...`, which classic patterns reject),
105
+ // while the open trust (matching every format) and non-classic literals
106
+ // render verbatim.
107
+ export function renderOidcSubClaim(sub) {
108
+ const companion = immutableCompanion(sub);
109
+ if (companion === null) return `"${sub}"`;
110
+ return `["${sub}", "${companion}"]`;
111
+ }
112
+
85
113
  // Classifies an existing tree's OIDC claim for re-init: a bare string (or
86
- // single-entry list, IAM-identical) renders verbatim; anything richer is
87
- // described for warnings and guarded against silent widening.
114
+ // single-entry list, IAM-identical) renders verbatim; our own canonical
115
+ // dual-format pair resolves back to its classic entry so re-init stays
116
+ // stable; anything richer is described for warnings and guarded against
117
+ // silent widening.
88
118
  function classifyTreeTrust(claim) {
89
119
  if (!claim) return { trust: null, complex: null };
90
120
  if (claim.kind === 'string') return { trust: claim.value, complex: null };
91
121
  if (claim.kind === 'list' && claim.entries.length === 1) {
92
122
  return { trust: claim.entries[0], complex: null };
93
123
  }
124
+ if (claim.kind === 'list' && claim.entries.length === 2
125
+ && immutableCompanion(claim.entries[0]) === claim.entries[1]) {
126
+ return { trust: claim.entries[0], complex: null };
127
+ }
94
128
  if (claim.kind === 'list') {
95
129
  const entries = claim.entries.length > 0 ? ` (${claim.entries.join(', ')})` : '';
96
130
  return { trust: null, complex: `${claim.entries.length}-entry list${entries}` };
@@ -780,7 +814,7 @@ async function mainStackMain(input = {}) {
780
814
  HEALTH_CHECK_PATH: config.healthCheckPath,
781
815
  DESIRED_COUNT: config.desiredCount,
782
816
  DEPLOY_BRANCH: config.branch,
783
- GITHUB_REPO_SUB: oidcTrustSub,
817
+ GITHUB_REPO_SUB: renderOidcSubClaim(oidcTrustSub),
784
818
  BUILD_DIR: buildDir,
785
819
  finalFramework: config.framework,
786
820
  NEEDS_DATABASE: config.needsDatabase,
@@ -3,7 +3,7 @@ import color from 'picocolors';
3
3
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
4
4
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
5
5
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
6
- import { resolveRegion, resolveProjectName, resolveLogGroup, resolveCwd, isComputeTarget } from '../utils/resolvers.js';
6
+ import { resolveRegion, resolveProjectName, resolveLogGroup, resolveCwd, isComputeTarget, withWorkspaceNamespace } from '../utils/resolvers.js';
7
7
  import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseUnknownFlags } from '../utils/command.js';
8
8
  import { sleep } from '../utils/system.js';
9
9
 
@@ -40,6 +40,18 @@ export function normalizeTailLines(value) {
40
40
  return n;
41
41
  }
42
42
 
43
+ function isValidTailLines(value) {
44
+ if (typeof value === 'number') return Number.isInteger(value) && value >= 1;
45
+ if (typeof value === 'string') return /^\d+$/.test(value.trim()) && parseInt(value, 10) >= 1;
46
+ return false;
47
+ }
48
+
49
+ function isValidSinceDuration(value) {
50
+ if (typeof value === 'number') return Number.isFinite(value);
51
+ if (typeof value === 'string') return SINCE_RE.test(value.trim());
52
+ return false;
53
+ }
54
+
43
55
  export function parseSinceDuration(input) {
44
56
  if (input === undefined || input === null || input === '') return UNIT_MS.h;
45
57
  if (typeof input === 'number' && Number.isFinite(input)) return Math.max(0, input * 1000);
@@ -86,7 +98,7 @@ export function parseLogsArgs(argv = []) {
86
98
  const args = normalizeArgv(argv);
87
99
  if (args[0] === 'logs') args.shift();
88
100
  const { options, rest, unknown } = parseFlags(args, {
89
- string: ['since', 'region'],
101
+ string: ['since', 'region', 'workspace'],
90
102
  number: ['tail'],
91
103
  boolean: ['headless'],
92
104
  bareBoolean: ['follow', 'error'],
@@ -103,6 +115,44 @@ function eventKey(event) {
103
115
  return `${event.timestamp}:${event.message}`;
104
116
  }
105
117
 
118
+ // Fetches the most recent matching events from a log group.
119
+ // FilterLogEvents pages oldest-first, so slicing the first page shows the
120
+ // OLDEST N on groups larger than one page (BUG-87). This probes with a
121
+ // small page (cheap when the group fits), and only multi-page groups pay
122
+ // for a wide-page scan to the live edge; a rolling window keeps memory
123
+ // O(tail). Returns `{ events, nextToken }` — the trailing window plus the
124
+ // last valid page token (for follow-mode continuation).
125
+ export async function fetchLatestEvents(logsClient, baseInput = {}, { tail = DEFAULT_TAIL_LINES, onlyErrors = false } = {}) {
126
+ const want = Math.max(1, tail);
127
+ const probeSize = Math.min(want, 10000);
128
+ const first = await logsClient.send(new FilterLogEventsCommand({ ...baseInput, limit: probeSize }));
129
+ if (!first.nextToken) {
130
+ const events = first.events || [];
131
+ return {
132
+ events: (onlyErrors ? events.filter((e) => isErrorLine(e.message)) : events).slice(-want),
133
+ nextToken: undefined,
134
+ };
135
+ }
136
+ const window = [];
137
+ let nextToken;
138
+ let lastToken;
139
+ do {
140
+ const resp = await logsClient.send(new FilterLogEventsCommand({
141
+ ...baseInput,
142
+ limit: 10000,
143
+ ...(nextToken ? { nextToken } : {}),
144
+ }));
145
+ const events = onlyErrors ? (resp.events || []).filter((e) => isErrorLine(e.message)) : (resp.events || []);
146
+ for (const event of events) {
147
+ window.push(event);
148
+ if (window.length > want) window.shift();
149
+ }
150
+ if (resp.nextToken) lastToken = resp.nextToken;
151
+ nextToken = resp.nextToken;
152
+ } while (nextToken);
153
+ return { events: window, nextToken: lastToken };
154
+ }
155
+
106
156
  export function isNotFoundError(error) {
107
157
  return error && (
108
158
  error.name === 'ResourceNotFoundException' ||
@@ -145,8 +195,12 @@ async function runLogsMain(input = {}) {
145
195
  try {
146
196
  cwd = resolveCwd(options);
147
197
  region = resolveRegion(options, cwd);
148
- service = resolveServiceName(options, cwd);
149
- logGroup = resolveLogGroup(options, cwd);
198
+ // Workspace-namespaced resources (BUG-90): --workspace (or the
199
+ // local .terraform/environment) targets a preview stack like
200
+ // rollback and db do. Explicit flags/env keep winning.
201
+ const namespacedOptions = withWorkspaceNamespace(options, cwd);
202
+ service = resolveServiceName(namespacedOptions, cwd);
203
+ logGroup = resolveLogGroup(namespacedOptions, cwd);
150
204
  } catch {
151
205
  return failProjectNotInitialized({ event: 'logs_streamed' });
152
206
  }
@@ -158,6 +212,32 @@ async function runLogsMain(input = {}) {
158
212
  const isLambda = isComputeTarget(cwd, 'lambda');
159
213
  const explicitService = hasExplicitService(options) && !isLambda;
160
214
 
215
+ // Explicit garbage fails loud (BUG-107): silently substituting defaults
216
+ // for a mistyped --tail/--since shows logs the user never asked for.
217
+ // Absent flags still default via the normalizers below.
218
+ const rawTail = options.tail ?? options.tailLines ?? options.lines;
219
+ if (rawTail !== undefined && !isValidTailLines(rawTail)) {
220
+ return failCommand({
221
+ noExit: isProgrammaticCall(options),
222
+ message: `\n✖ Invalid --tail "${rawTail}". Pass a positive integer (line count).\n`,
223
+ event: 'logs_streamed',
224
+ telemetry: { projectName: resolveProjectName(options, cwd) },
225
+ errorCode: 'INVALID_TAIL',
226
+ reason: 'invalid-tail',
227
+ });
228
+ }
229
+ const rawSince = options.since ?? options.sinceDuration;
230
+ if (rawSince !== undefined && !isValidSinceDuration(rawSince)) {
231
+ return failCommand({
232
+ noExit: isProgrammaticCall(options),
233
+ message: `\n✖ Invalid --since "${rawSince}". Pass a duration like 30s, 5m, 1h, or 7d.\n`,
234
+ event: 'logs_streamed',
235
+ telemetry: { projectName: resolveProjectName(options, cwd) },
236
+ errorCode: 'INVALID_SINCE',
237
+ reason: 'invalid-since',
238
+ });
239
+ }
240
+
161
241
  const sinceRaw = options.since ?? options.sinceDuration ?? (follow ? undefined : DEFAULT_SINCE);
162
242
  const startTime = sinceRaw === undefined ? undefined : Date.now() - parseSinceDuration(sinceRaw);
163
243
 
@@ -194,40 +274,47 @@ async function runLogsMain(input = {}) {
194
274
 
195
275
  const seen = new Set();
196
276
  const collected = [];
197
- let nextToken;
198
- let polls = 0;
199
- let firstPoll = true;
200
-
201
- do {
202
- const input = { logGroupName: logGroup, limit: Math.min(Math.max(tail, 1), 10000) };
203
- if (startTime !== undefined) input.startTime = startTime;
204
- if (explicitService) input.logStreamNamePrefix = service;
205
- if (nextToken) input.nextToken = nextToken;
206
-
207
- const resp = await logsClient.send(new FilterLogEventsCommand(input));
208
- if (resp.nextToken) nextToken = resp.nextToken;
209
-
210
- if (seen.size > 5000) seen.clear();
211
-
212
- let fresh = (resp.events || []).filter((e) => {
213
- const key = eventKey(e);
214
- if (seen.has(key)) return false;
215
- seen.add(key);
216
- return true;
217
- });
218
- if (onlyErrors) fresh = fresh.filter((e) => isErrorLine(e.message));
219
- if (firstPoll) fresh = fresh.slice(-tail);
220
-
221
- for (const event of fresh) {
222
- console.log(formatLogLine(event));
223
- collected.push(String(event.message ?? ''));
224
- }
277
+ const dedupe = (e) => {
278
+ const key = eventKey(e);
279
+ if (seen.has(key)) return false;
280
+ seen.add(key);
281
+ return true;
282
+ };
283
+ const baseInput = { logGroupName: logGroup };
284
+ if (startTime !== undefined) baseInput.startTime = startTime;
285
+ if (explicitService) baseInput.logStreamNamePrefix = service;
286
+
287
+ // First poll starts at the live edge (see fetchLatestEvents):
288
+ // slicing an unscanned first page would show the OLDEST N.
289
+ const edge = await fetchLatestEvents(logsClient, baseInput, { tail, onlyErrors });
290
+ let nextToken = edge.nextToken;
291
+ let polls = 1;
292
+ for (const event of edge.events.filter(dedupe)) {
293
+ console.log(formatLogLine(event));
294
+ collected.push(String(event.message ?? ''));
295
+ }
296
+ if (follow && !stopped && polls < maxPolls) {
297
+ do {
298
+ await sleep(pollIntervalMs);
299
+ const input = { ...baseInput, limit: Math.min(Math.max(tail, 1), 10000) };
300
+ if (nextToken) input.nextToken = nextToken;
301
+
302
+ const resp = await logsClient.send(new FilterLogEventsCommand(input));
303
+ if (resp.nextToken) nextToken = resp.nextToken;
304
+
305
+ if (seen.size > 5000) seen.clear();
225
306
 
226
- firstPoll = false;
227
- polls += 1;
228
- if (!follow || stopped || polls >= maxPolls) break;
229
- await sleep(pollIntervalMs);
230
- } while (true);
307
+ let fresh = (resp.events || []).filter(dedupe);
308
+ if (onlyErrors) fresh = fresh.filter((e) => isErrorLine(e.message));
309
+
310
+ for (const event of fresh) {
311
+ console.log(formatLogLine(event));
312
+ collected.push(String(event.message ?? ''));
313
+ }
314
+
315
+ polls += 1;
316
+ } while (!stopped && polls < maxPolls);
317
+ }
231
318
 
232
319
  if (collected.length === 0) {
233
320
  console.log(color.cyan(`\nℹ Waiting for logs...`));
@@ -452,7 +452,7 @@ export function resolveMcpTransport(input = {}) {
452
452
  // every OS layout from one machine.
453
453
  export const MCP_INSTALL_EDITORS = ['windsurf', 'zed', 'cursor', 'vscode', 'claude-desktop', 'gemini-cli'];
454
454
 
455
- export const MCP_SERVER_CONFIG = { command: 'npx', args: ['grada-run', 'mcp'] };
455
+ export const MCP_SERVER_CONFIG = { command: 'npx', args: ['--yes', 'grada-run', 'mcp'] };
456
456
 
457
457
  export function mcpInstallTarget(editor, homeDir = safeHomedir(), platform = os.platform()) {
458
458
  // No home, no target: null reads as "unresolvable" like an unknown