grada-run 0.40.11 → 0.40.13
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/package.json +1 -1
- package/src/commands/add.js +49 -5
- package/src/commands/alerts.js +22 -8
- package/src/commands/apply.js +30 -2
- package/src/commands/db/backup.js +25 -0
- package/src/commands/destroy.js +33 -2
- package/src/commands/diagnose.js +59 -41
- package/src/commands/domain.js +67 -23
- package/src/commands/eject.js +26 -2
- package/src/commands/exec.js +21 -18
- package/src/commands/gc.js +142 -21
- package/src/commands/init.js +24 -3
- package/src/commands/mcp.js +74 -0
- package/src/commands/rollback.js +28 -2
- package/src/commands/secrets.js +98 -45
- package/src/commands/sleep.js +10 -11
- package/src/commands/sync-ai.js +18 -5
- package/src/utils/ai-rules.js +10 -0
- package/src/utils/command.js +27 -0
- package/src/utils/ecs.js +30 -0
- package/src/utils/recovery.js +19 -1
- package/src/utils/sleep-state.js +2 -2
- package/src/utils/terraform-metadata.js +2 -1
package/src/commands/domain.js
CHANGED
|
@@ -6,7 +6,7 @@ import { intro, outro, confirm, cancel, isCancel } from '@clack/prompts';
|
|
|
6
6
|
import { trackSuccess, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
|
|
7
7
|
import { resolveProjectName, resolveHeadless, resolveCwd } from '../utils/resolvers.js';
|
|
8
8
|
import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
|
|
9
|
-
import { failCommand, failProjectNotInitialized, isProgrammaticCall } from '../utils/command.js';
|
|
9
|
+
import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseIfNonInteractive } from '../utils/command.js';
|
|
10
10
|
import { getTerraformOutputs } from '../utils/terraform.js';
|
|
11
11
|
import {
|
|
12
12
|
findResourceBlock,
|
|
@@ -266,25 +266,39 @@ export function patchCloudFrontDomain(cloudfrontTfContent, domain) {
|
|
|
266
266
|
return head + block + tail;
|
|
267
267
|
}
|
|
268
268
|
|
|
269
|
-
//
|
|
270
|
-
//
|
|
271
|
-
|
|
272
|
-
|
|
269
|
+
// Alias domains currently wired on the CloudFront distribution (the
|
|
270
|
+
// workspace-conditional true-branch list), or [] when unwired.
|
|
271
|
+
export function getCloudFrontAliases(cloudfrontTfContent) {
|
|
272
|
+
const content = String(cloudfrontTfContent ?? '');
|
|
273
|
+
const resource = findResourceBlock(content, 'aws_cloudfront_distribution', 'cdn');
|
|
274
|
+
if (!resource) return [];
|
|
275
|
+
const block = content.slice(resource.openIdx, resource.closeIdx + 1);
|
|
276
|
+
const current = getAttributeValue(block, 'aliases');
|
|
277
|
+
if (current === null) return [];
|
|
278
|
+
return parseAliasesValue(current);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Removes `domain` from the `aliases`, restoring the default CloudFront
|
|
282
|
+
// certificate only when no aliases remain — remaining aliases require
|
|
283
|
+
// an ACM certificate (CloudFront rejects the default cert with any
|
|
284
|
+
// alias). Idempotent; returns the content unchanged when the
|
|
285
|
+
// distribution is missing or the domain is not wired.
|
|
273
286
|
export function unpatchCloudFrontDomain(cloudfrontTfContent, domain) {
|
|
274
287
|
const content = String(cloudfrontTfContent ?? '');
|
|
275
288
|
const resource = findResourceBlock(content, 'aws_cloudfront_distribution', 'cdn');
|
|
276
289
|
if (!resource) return content;
|
|
290
|
+
const aliases = getCloudFrontAliases(content);
|
|
291
|
+
if (!aliases.includes(domain)) return content;
|
|
277
292
|
const head = content.slice(0, resource.openIdx);
|
|
278
293
|
const tail = content.slice(resource.closeIdx + 1);
|
|
279
294
|
let block = content.slice(resource.openIdx, resource.closeIdx + 1);
|
|
280
|
-
const
|
|
281
|
-
if (
|
|
282
|
-
|
|
283
|
-
block =
|
|
284
|
-
|
|
285
|
-
|
|
295
|
+
const remaining = aliases.filter((entry) => entry !== domain);
|
|
296
|
+
if (remaining.length === 0) {
|
|
297
|
+
block = removeAttribute(block, 'aliases');
|
|
298
|
+
block = replaceViewerCertificate(block, DEFAULT_VIEWER_CERTIFICATE);
|
|
299
|
+
} else {
|
|
300
|
+
block = upsertAttribute(block, 'aliases', renderConditionalAliasesList(remaining));
|
|
286
301
|
}
|
|
287
|
-
block = replaceViewerCertificate(block, DEFAULT_VIEWER_CERTIFICATE);
|
|
288
302
|
return head + block + tail;
|
|
289
303
|
}
|
|
290
304
|
|
|
@@ -676,18 +690,41 @@ async function runDomainRemove({ options, projectName, domainTfPath, cloudfrontT
|
|
|
676
690
|
const domain = parsed?.domain;
|
|
677
691
|
const mode = parsed?.mode || 'unknown';
|
|
678
692
|
const yes = options.yes === true;
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
693
|
+
const readRemainingAliases = () => {
|
|
694
|
+
try {
|
|
695
|
+
if (!domain || !fsSync.existsSync(cloudfrontTfPath)) return null;
|
|
696
|
+
return getCloudFrontAliases(fsSync.readFileSync(cloudfrontTfPath, 'utf-8')).filter((entry) => entry !== domain);
|
|
697
|
+
} catch {
|
|
698
|
+
return null;
|
|
699
|
+
}
|
|
700
|
+
};
|
|
701
|
+
if (!yes) {
|
|
702
|
+
const refused = await refuseIfNonInteractive(options, {
|
|
703
|
+
message: `\n✖ domain needs confirmation before removing the custom domain.`,
|
|
704
|
+
hint: ' Re-run with --yes to remove non-interactively.\n',
|
|
683
705
|
event: 'domain_run',
|
|
684
|
-
telemetry: { projectName
|
|
685
|
-
|
|
686
|
-
resultExtra: { subcommand: 'remove', projectName },
|
|
706
|
+
telemetry: { projectName },
|
|
707
|
+
errorCode: 'DOMAIN_NON_INTERACTIVE',
|
|
687
708
|
});
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
709
|
+
if (refused) return refused;
|
|
710
|
+
// Explicit non-interactive flags without --yes keep the
|
|
711
|
+
// historical refusal (the gate above fires inferred-headless
|
|
712
|
+
// only, so any headless run reaching here was explicitly asked).
|
|
713
|
+
if (resolveHeadless(options)) {
|
|
714
|
+
return failCommand({
|
|
715
|
+
noExit,
|
|
716
|
+
message: '\n✖ Refusing to remove the custom domain without confirmation. Re-run with --yes.\n',
|
|
717
|
+
event: 'domain_run',
|
|
718
|
+
telemetry: { projectName, subcommand: 'remove', error_code: 'CONFIRMATION_REQUIRED' },
|
|
719
|
+
reason: 'confirmation-required',
|
|
720
|
+
resultExtra: { subcommand: 'remove', projectName },
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
const previewRemaining = readRemainingAliases();
|
|
724
|
+
const prompt = previewRemaining && previewRemaining.length > 0
|
|
725
|
+
? `Remove custom domain ${domain || '(unparseable)'}? ${previewRemaining.length} other alias(es) (${previewRemaining.join(', ')}) will keep the ACM certificate wiring.`
|
|
726
|
+
: `Remove custom domain ${domain || '(unparseable)'} and restore the default CloudFront certificate?`;
|
|
727
|
+
const answer = await confirm({ message: prompt });
|
|
691
728
|
if (isCancel(answer) || !answer) {
|
|
692
729
|
return failCommand({
|
|
693
730
|
noExit,
|
|
@@ -699,18 +736,25 @@ async function runDomainRemove({ options, projectName, domainTfPath, cloudfrontT
|
|
|
699
736
|
});
|
|
700
737
|
}
|
|
701
738
|
}
|
|
739
|
+
let remainingAliases = [];
|
|
702
740
|
try {
|
|
703
741
|
if (domain && fsSync.existsSync(cloudfrontTfPath)) {
|
|
704
742
|
const content = fsSync.readFileSync(cloudfrontTfPath, 'utf-8');
|
|
705
743
|
const updated = unpatchCloudFrontDomain(content, domain);
|
|
706
744
|
if (updated !== content) atomicWriteFileSync(cloudfrontTfPath, updated);
|
|
745
|
+
remainingAliases = getCloudFrontAliases(updated).filter((entry) => entry !== domain);
|
|
707
746
|
}
|
|
708
747
|
} catch {
|
|
709
748
|
// A best-effort unpatch never blocks domain.tf removal.
|
|
710
749
|
}
|
|
711
750
|
ensureUsEast1Provider(path.join(path.dirname(domainTfPath), 'main.tf'));
|
|
712
751
|
fsSync.rmSync(domainTfPath, { force: true });
|
|
713
|
-
|
|
752
|
+
if (remainingAliases.length > 0) {
|
|
753
|
+
console.log(color.green(`\n✅ Custom domain ${domain || ''} removed.`.replace(' ', ' ')));
|
|
754
|
+
console.log(color.yellow(`⚠ ${remainingAliases.length} alias(es) remain (${remainingAliases.join(', ')}): the ACM viewer_certificate is kept, but its validation resource is deleted with domain.tf — rewire the certificate by hand before applying.`));
|
|
755
|
+
} else {
|
|
756
|
+
console.log(color.green(`\n✅ Custom domain ${domain || ''} removed; CloudFront restored to the default certificate.`.replace(' ', ' ')));
|
|
757
|
+
}
|
|
714
758
|
console.log(` Run ${color.green('npx grada-run apply')} to push the change.`);
|
|
715
759
|
outro(color.green('Done.'));
|
|
716
760
|
await trackSuccess('domain_run', { projectName, subcommand: 'remove', mode });
|
package/src/commands/eject.js
CHANGED
|
@@ -3,7 +3,7 @@ import path from 'path';
|
|
|
3
3
|
import { intro, outro, confirm, spinner, cancel } from '@clack/prompts';
|
|
4
4
|
import color from 'picocolors';
|
|
5
5
|
import { trackEvent, flushTelemetry, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
|
|
6
|
-
import { failCommand, shouldAutoApprove } from '../utils/command.js';
|
|
6
|
+
import { failCommand, refuseIfNonInteractive, shouldAutoApprove } from '../utils/command.js';
|
|
7
7
|
import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
|
|
8
8
|
import {
|
|
9
9
|
stripTerraformMetadata,
|
|
@@ -28,6 +28,12 @@ export function parseEjectArgs(argv = []) {
|
|
|
28
28
|
// Re-exported so existing importers (tests) keep working unchanged.
|
|
29
29
|
export { stripTerraformMetadata, stripGitignoreMetadata };
|
|
30
30
|
|
|
31
|
+
// Grada's own backups are exactly `<name>.bak.<Date.now()>` — match that
|
|
32
|
+
// shape only so user files merely containing `.bak.` survive the purge.
|
|
33
|
+
export function isGradaBackupName(fileName) {
|
|
34
|
+
return /^.+\.bak\.\d+$/.test(String(fileName ?? ''));
|
|
35
|
+
}
|
|
36
|
+
|
|
31
37
|
function collectTerraformFiles(dir, out = []) {
|
|
32
38
|
if (!fs.existsSync(dir)) return out;
|
|
33
39
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
@@ -87,6 +93,14 @@ async function ejectStackMain(input = {}) {
|
|
|
87
93
|
reason: 'eject-while-asleep',
|
|
88
94
|
});
|
|
89
95
|
}
|
|
96
|
+
const refused = await refuseIfNonInteractive(options, {
|
|
97
|
+
message: `\n✖ eject needs approval before waking the asleep stack.`,
|
|
98
|
+
hint: ' Run npx grada-run wake first, or re-run with --force to eject anyway (the ledger migrates to SLEEPING.md).\n',
|
|
99
|
+
event: 'project_ejected',
|
|
100
|
+
telemetry: { projectName },
|
|
101
|
+
errorCode: 'EJECT_NON_INTERACTIVE',
|
|
102
|
+
});
|
|
103
|
+
if (refused) return refused;
|
|
90
104
|
const wakeFirst = await confirm({
|
|
91
105
|
message: 'The stack is asleep. Wake it now and continue with eject?',
|
|
92
106
|
initialValue: true,
|
|
@@ -118,6 +132,16 @@ async function ejectStackMain(input = {}) {
|
|
|
118
132
|
await flushTelemetry();
|
|
119
133
|
}
|
|
120
134
|
|
|
135
|
+
if (!shouldAutoApprove(options)) {
|
|
136
|
+
const refused = await refuseIfNonInteractive(options, {
|
|
137
|
+
message: `\n✖ eject needs confirmation before decoupling infrastructure from the grada CLI.`,
|
|
138
|
+
hint: ' Re-run with --yes to eject non-interactively.\n',
|
|
139
|
+
event: 'project_ejected',
|
|
140
|
+
telemetry: { projectName },
|
|
141
|
+
errorCode: 'EJECT_NON_INTERACTIVE',
|
|
142
|
+
});
|
|
143
|
+
if (refused) return refused;
|
|
144
|
+
}
|
|
121
145
|
const shouldEject = shouldAutoApprove(options) ? true : await confirm({
|
|
122
146
|
message: 'Are you sure you want to eject? (This cannot be undone)',
|
|
123
147
|
initialValue: false,
|
|
@@ -162,7 +186,7 @@ async function ejectStackMain(input = {}) {
|
|
|
162
186
|
const files = fs.readdirSync(dir);
|
|
163
187
|
for (const file of files) {
|
|
164
188
|
const fullPath = path.join(dir, file);
|
|
165
|
-
if (file
|
|
189
|
+
if (isGradaBackupName(file)) {
|
|
166
190
|
fs.rmSync(fullPath, { recursive: true, force: true });
|
|
167
191
|
} else if (fs.statSync(fullPath).isDirectory() && file !== 'node_modules' && file !== '.git') {
|
|
168
192
|
cleanBackups(fullPath); // Recursively check subdirectories like .github/workflows
|
package/src/commands/exec.js
CHANGED
|
@@ -2,7 +2,7 @@ import { ECSClient, ListTasksCommand, DescribeTasksCommand } from '@aws-sdk/clie
|
|
|
2
2
|
import { spawn } from 'child_process';
|
|
3
3
|
import color from 'picocolors';
|
|
4
4
|
import { intro, outro, spinner } from '@clack/prompts';
|
|
5
|
-
import { trackEvent, flushTelemetry, trackSuccess, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
|
|
5
|
+
import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
|
|
6
6
|
import { hasAwsCli, AWS_CLI_INSTALL_URL, isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
|
|
7
7
|
import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized, isProgrammaticCall } from '../utils/command.js';
|
|
8
8
|
import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
|
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
printAwsCliGuidance,
|
|
14
14
|
printSessionManagerGuidance,
|
|
15
15
|
printNoTasksGuidance,
|
|
16
|
+
pickNewestRunningTask,
|
|
16
17
|
} from '../utils/ecs.js';
|
|
17
18
|
|
|
18
19
|
// Re-exported from the shared ECS module for backward compatibility.
|
|
@@ -73,11 +74,11 @@ export async function findRunningTask(ecsClient, { cluster, service }) {
|
|
|
73
74
|
const taskArns = listResp.taskArns || [];
|
|
74
75
|
if (taskArns.length === 0) return null;
|
|
75
76
|
const descResp = await ecsClient.send(
|
|
76
|
-
new DescribeTasksCommand({ cluster, tasks: taskArns.slice(0,
|
|
77
|
+
new DescribeTasksCommand({ cluster, tasks: taskArns.slice(0, 10) })
|
|
77
78
|
);
|
|
78
|
-
const
|
|
79
|
-
if (
|
|
80
|
-
return { taskArn:
|
|
79
|
+
const newest = pickNewestRunningTask(descResp.tasks || []);
|
|
80
|
+
if (!newest) return null;
|
|
81
|
+
return { taskArn: newest.taskArn || taskArns[0], containerName: newest.containers?.[0]?.name || null, task: newest };
|
|
81
82
|
}
|
|
82
83
|
|
|
83
84
|
// Programmatic entry wrapper: stamps cli_command for telemetry on every
|
|
@@ -211,27 +212,29 @@ async function runExecMain(input = {}) {
|
|
|
211
212
|
region,
|
|
212
213
|
});
|
|
213
214
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
await new Promise((resolve) => {
|
|
215
|
+
const { code } = await new Promise((resolve) => {
|
|
217
216
|
const child = spawnImpl('aws', cliArgs, { stdio: 'inherit' });
|
|
218
217
|
child.on('error', (err) => {
|
|
219
218
|
console.log(color.red(`\n✖ Failed to start AWS CLI: ${err?.message || err}`));
|
|
220
219
|
console.log(color.dim(`Install help: ${AWS_CLI_INSTALL_URL}`));
|
|
221
220
|
resolve({ code: 1 });
|
|
222
221
|
});
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
outro(color.green('Shell session ended. 👋'));
|
|
227
|
-
} else {
|
|
228
|
-
console.log(color.yellow(`\nShell exited with code ${code}.`));
|
|
229
|
-
console.log(color.dim(`If the connection failed, ensure ECS Exec is enabled (re-run ${color.green('npx grada-run apply')}) and the Session Manager plugin is installed.`));
|
|
230
|
-
outro(color.yellow('Exec finished.'));
|
|
231
|
-
}
|
|
222
|
+
// A null close code means the process died by signal — never
|
|
223
|
+
// report that as success.
|
|
224
|
+
child.on('close', (code) => resolve({ code: code ?? 1 }));
|
|
232
225
|
});
|
|
233
226
|
|
|
234
|
-
|
|
227
|
+
if (code === 0) {
|
|
228
|
+
outro(color.green('Shell session ended. 👋'));
|
|
229
|
+
await trackSuccess('exec_run', { projectName, exit_code: 0 });
|
|
230
|
+
} else {
|
|
231
|
+
console.log(color.yellow(`\nShell exited with code ${code}.`));
|
|
232
|
+
console.log(color.dim(`If the connection failed, ensure ECS Exec is enabled (re-run ${color.green('npx grada-run apply')}) and the Session Manager plugin is installed.`));
|
|
233
|
+
outro(color.yellow('Exec finished.'));
|
|
234
|
+
await trackFailure('exec_run', { projectName, error_code: 'EXEC_SESSION_FAILED', exit_code: code });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
return { ok: code === 0, exitCode: code, cluster, service, taskArn, container: resolvedContainer, region };
|
|
235
238
|
} catch (error) {
|
|
236
239
|
if (isAuthError(error)) {
|
|
237
240
|
await trackAwsFailure('exec_run', error, { projectName });
|
package/src/commands/gc.js
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
2
|
import path from 'path';
|
|
3
|
+
import { spawnSync } from 'child_process';
|
|
3
4
|
import { ECRClient, DescribeRepositoriesCommand, DescribeImagesCommand, BatchDeleteImageCommand } from '@aws-sdk/client-ecr';
|
|
4
5
|
import { CloudWatchLogsClient, DescribeLogGroupsCommand, DeleteLogGroupCommand } from '@aws-sdk/client-cloudwatch-logs';
|
|
6
|
+
import { ECSClient, ListServicesCommand } from '@aws-sdk/client-ecs';
|
|
5
7
|
import { EC2Client, DescribeAddressesCommand, ReleaseAddressCommand, DescribeVpcsCommand } from '@aws-sdk/client-ec2';
|
|
6
8
|
import { SecretsManagerClient, ListSecretsCommand } from '@aws-sdk/client-secrets-manager';
|
|
7
9
|
import color from 'picocolors';
|
|
8
10
|
import { intro, outro, confirm, spinner, cancel } from '@clack/prompts';
|
|
9
11
|
import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
|
|
10
12
|
import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
|
|
11
|
-
import { resolveRegion, resolveProjectName, resolveCwd, isComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
|
|
13
|
+
import { resolveRegion, resolveProjectName, resolveCluster, resolveCwd, isComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
|
|
12
14
|
import { resolveClient } from '../utils/aws.js';
|
|
13
|
-
import { failCommand, failProjectNotInitialized, isProgrammaticCall, shouldAutoApprove } from '../utils/command.js';
|
|
15
|
+
import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseIfNonInteractive, shouldAutoApprove } from '../utils/command.js';
|
|
14
16
|
import { parseStateBucketBackend } from '../utils/terraform-metadata.js';
|
|
15
17
|
|
|
16
18
|
export const CONFIRM_MESSAGE = 'Are you sure you want to permanently delete these orphaned resources? (y/N)';
|
|
@@ -58,20 +60,36 @@ export function hasExactProjectTag(tags, projectName) {
|
|
|
58
60
|
);
|
|
59
61
|
}
|
|
60
62
|
|
|
61
|
-
function
|
|
62
|
-
return
|
|
63
|
+
function escapeRegExp(text) {
|
|
64
|
+
return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
63
65
|
}
|
|
64
66
|
|
|
65
|
-
//
|
|
66
|
-
//
|
|
67
|
-
|
|
67
|
+
// Grada renders exactly one ECR repo per tree: `<project><suffix>-repo`
|
|
68
|
+
// (previews push tags; they never mint repos). Anything else sharing
|
|
69
|
+
// the prefix is foreign — never propose it.
|
|
70
|
+
function projectRepoName(projectName, resourceSuffix = '') {
|
|
71
|
+
return `${projectName}${resourceSuffix}-repo`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Preview log groups carry the `-pr-<n>` workspace infix at a fixed
|
|
75
|
+
// position (`<project>-pr-<n><suffix>`); anchor both ends so foreign
|
|
76
|
+
// lookalikes (`myapp-evil-pr-2`) never match.
|
|
77
|
+
function previewLogGroupPattern({ projectName, resourceSuffix = '', isLambda = false }) {
|
|
78
|
+
const base = `${escapeRegExp(projectName)}-pr-\\d+${escapeRegExp(resourceSuffix)}`;
|
|
79
|
+
return isLambda ? new RegExp(`^/aws/lambda/${base}-fn$`) : new RegExp(`^/ecs/${base}$`);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Standard target discovery: untagged ECR images in the project's own
|
|
83
|
+
// repo. Both DescribeRepositories and DescribeImages are paginated.
|
|
84
|
+
async function discoverUntaggedImages({ ecrClient, projectName, resourceSuffix = '' }) {
|
|
68
85
|
const untaggedImages = [];
|
|
69
86
|
const repositories = [];
|
|
87
|
+
const ownRepo = projectRepoName(projectName, resourceSuffix);
|
|
70
88
|
let reposNextToken;
|
|
71
89
|
do {
|
|
72
90
|
const reposResp = await ecrClient.send(new DescribeRepositoriesCommand({ nextToken: reposNextToken }));
|
|
73
91
|
for (const repo of reposResp.repositories || []) {
|
|
74
|
-
if (
|
|
92
|
+
if (repo.repositoryName === ownRepo) repositories.push(repo);
|
|
75
93
|
}
|
|
76
94
|
reposNextToken = reposResp.nextToken;
|
|
77
95
|
} while (reposNextToken);
|
|
@@ -96,26 +114,98 @@ async function discoverUntaggedImages({ ecrClient, projectName }) {
|
|
|
96
114
|
return untaggedImages;
|
|
97
115
|
}
|
|
98
116
|
|
|
117
|
+
// Lambda function listing without a new SDK dependency, mirroring
|
|
118
|
+
// diagnose's AWS CLI usage. Throws when the CLI is missing, fails, or
|
|
119
|
+
// returns unparseable output — the caller treats that as unknown.
|
|
120
|
+
function defaultListLambdaFunctionNames({ region, spawnSyncImpl } = {}) {
|
|
121
|
+
const runSync = spawnSyncImpl || spawnSync;
|
|
122
|
+
const res = runSync('aws', [
|
|
123
|
+
'lambda', 'list-functions',
|
|
124
|
+
'--query', 'Functions[].FunctionName',
|
|
125
|
+
'--output', 'json',
|
|
126
|
+
...(region ? ['--region', region] : []),
|
|
127
|
+
], { encoding: 'utf-8' });
|
|
128
|
+
if (res?.status !== 0 || res?.error) {
|
|
129
|
+
throw new Error(res?.error?.message || String(res?.stderr || 'aws lambda list-functions failed').trim());
|
|
130
|
+
}
|
|
131
|
+
const names = JSON.parse(String(res.stdout || '[]'));
|
|
132
|
+
if (!Array.isArray(names)) throw new Error('unexpected list-functions output');
|
|
133
|
+
return names;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Log groups whose preview compute still exists: ECS services for Fargate
|
|
137
|
+
// trees, Lambda functions for serverless ones. Never throws — any scan
|
|
138
|
+
// failure resolves to `unknown` so discovery fails closed instead of
|
|
139
|
+
// proposing live-preview groups.
|
|
140
|
+
export async function discoverLivePreviewLogGroups({
|
|
141
|
+
ecsClient = null,
|
|
142
|
+
cluster = null,
|
|
143
|
+
projectName,
|
|
144
|
+
resourceSuffix = '',
|
|
145
|
+
isLambda = false,
|
|
146
|
+
listFunctionsImpl = defaultListLambdaFunctionNames,
|
|
147
|
+
spawnSyncImpl = null,
|
|
148
|
+
region = null,
|
|
149
|
+
} = {}) {
|
|
150
|
+
const live = new Set();
|
|
151
|
+
try {
|
|
152
|
+
const base = `${escapeRegExp(projectName)}-pr-\\d+${escapeRegExp(resourceSuffix)}`;
|
|
153
|
+
if (isLambda) {
|
|
154
|
+
const fnPattern = new RegExp(`^${base}-fn$`);
|
|
155
|
+
const names = await listFunctionsImpl({ region, spawnSyncImpl });
|
|
156
|
+
for (const name of names || []) {
|
|
157
|
+
if (typeof name === 'string' && fnPattern.test(name)) live.add(`/aws/lambda/${name}`);
|
|
158
|
+
}
|
|
159
|
+
} else {
|
|
160
|
+
if (!ecsClient || !cluster) return { groups: live, unknown: false };
|
|
161
|
+
const servicePattern = new RegExp(`^${base}-service$`);
|
|
162
|
+
let nextToken;
|
|
163
|
+
do {
|
|
164
|
+
const resp = await ecsClient.send(new ListServicesCommand({ cluster, nextToken, maxResults: 100 }));
|
|
165
|
+
for (const arn of resp.serviceArns || []) {
|
|
166
|
+
const name = String(arn).split('/').pop();
|
|
167
|
+
if (servicePattern.test(name)) live.add(`/ecs/${name.slice(0, -'-service'.length)}`);
|
|
168
|
+
}
|
|
169
|
+
nextToken = resp.nextToken;
|
|
170
|
+
} while (nextToken);
|
|
171
|
+
}
|
|
172
|
+
} catch {
|
|
173
|
+
return { groups: live, unknown: true };
|
|
174
|
+
}
|
|
175
|
+
return { groups: live, unknown: false };
|
|
176
|
+
}
|
|
177
|
+
|
|
99
178
|
// Standard target discovery: orphaned CloudWatch log groups for deleted
|
|
100
|
-
// preview environments.
|
|
101
|
-
// (
|
|
102
|
-
//
|
|
103
|
-
//
|
|
104
|
-
async function discoverOrphanedLogGroups({
|
|
179
|
+
// preview environments. Candidates must match the anchored preview shape
|
|
180
|
+
// (foreign lookalikes rejected), must not be the live group, and must
|
|
181
|
+
// not belong to a still-running preview. When liveness is unknown the
|
|
182
|
+
// scan fails closed and proposes nothing.
|
|
183
|
+
async function discoverOrphanedLogGroups({
|
|
184
|
+
logsClient,
|
|
185
|
+
projectName,
|
|
186
|
+
logGroupPrefix,
|
|
187
|
+
excludeLogGroup,
|
|
188
|
+
resourceSuffix = '',
|
|
189
|
+
isLambda = false,
|
|
190
|
+
livePreviewGroups = null,
|
|
191
|
+
previewLivenessUnknown = false,
|
|
192
|
+
}) {
|
|
193
|
+
if (previewLivenessUnknown) return [];
|
|
105
194
|
const orphanedLogGroups = [];
|
|
106
195
|
const groupPrefix = logGroupPrefix || `/ecs/${projectName}-`;
|
|
196
|
+
const previewPattern = previewLogGroupPattern({ projectName, resourceSuffix, isLambda });
|
|
197
|
+
const live = livePreviewGroups instanceof Set ? livePreviewGroups : new Set();
|
|
107
198
|
let nextToken;
|
|
108
199
|
do {
|
|
109
200
|
const logsResp = await logsClient.send(
|
|
110
201
|
new DescribeLogGroupsCommand({ logGroupNamePrefix: groupPrefix, nextToken })
|
|
111
202
|
);
|
|
112
203
|
for (const group of logsResp.logGroups || []) {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
if (
|
|
117
|
-
|
|
118
|
-
}
|
|
204
|
+
const name = group.logGroupName;
|
|
205
|
+
if (!name || name === excludeLogGroup) continue;
|
|
206
|
+
if (!previewPattern.test(name)) continue;
|
|
207
|
+
if (live.has(name)) continue;
|
|
208
|
+
orphanedLogGroups.push({ logGroupName: name, storedBytes: group.storedBytes });
|
|
119
209
|
}
|
|
120
210
|
nextToken = logsResp.nextToken;
|
|
121
211
|
} while (nextToken);
|
|
@@ -383,6 +473,7 @@ async function runGcMain(input = {}) {
|
|
|
383
473
|
const ecrClient = resolveClient(options.ecrClient, ECRClient, { region });
|
|
384
474
|
const logsClient = resolveClient(options.logsClient, CloudWatchLogsClient, { region });
|
|
385
475
|
const ec2Client = resolveClient(options.ec2Client, EC2Client, { region });
|
|
476
|
+
const ecsClient = resolveClient(options.ecsClient, ECSClient, { region });
|
|
386
477
|
const secretsClient = resolveClient(options.secretsClient, SecretsManagerClient, { region });
|
|
387
478
|
const deep = options.deep === true || options.deep === 'true';
|
|
388
479
|
|
|
@@ -392,18 +483,35 @@ async function runGcMain(input = {}) {
|
|
|
392
483
|
s.start('Scanning for orphaned resources (dry run)...');
|
|
393
484
|
|
|
394
485
|
let discovered;
|
|
486
|
+
let previewLivenessUnknown = false;
|
|
395
487
|
try {
|
|
396
488
|
const isLambda = isComputeTarget(cwd, 'lambda');
|
|
489
|
+
const suffix = readResourceSuffix(cwd);
|
|
490
|
+
const liveness = await discoverLivePreviewLogGroups({
|
|
491
|
+
ecsClient,
|
|
492
|
+
cluster: resolveCluster(options, cwd),
|
|
493
|
+
projectName,
|
|
494
|
+
resourceSuffix: suffix,
|
|
495
|
+
isLambda,
|
|
496
|
+
spawnSyncImpl: options.spawnSyncImpl,
|
|
497
|
+
region,
|
|
498
|
+
});
|
|
499
|
+
previewLivenessUnknown = liveness.unknown;
|
|
397
500
|
discovered = await discoverOrphanedResources({
|
|
398
501
|
ecrClient,
|
|
399
502
|
logsClient,
|
|
400
503
|
ec2Client,
|
|
401
504
|
projectName,
|
|
505
|
+
resourceSuffix: suffix,
|
|
506
|
+
isLambda,
|
|
402
507
|
logGroupPrefix: isLambda ? `/aws/lambda/${projectName}-` : undefined,
|
|
403
508
|
// Exact match: the live group carries the suffix on suffixed
|
|
404
509
|
// trees, and proposing it for deletion would be catastrophic.
|
|
405
|
-
|
|
406
|
-
|
|
510
|
+
excludeLogGroup: isLambda
|
|
511
|
+
? `/aws/lambda/${projectName}${suffix}-fn`
|
|
512
|
+
: `/ecs/${projectName}${suffix}`,
|
|
513
|
+
livePreviewGroups: liveness.groups,
|
|
514
|
+
previewLivenessUnknown: liveness.unknown,
|
|
407
515
|
});
|
|
408
516
|
} catch (error) {
|
|
409
517
|
s.stop(color.red('❌ Discovery failed.'));
|
|
@@ -416,6 +524,9 @@ async function runGcMain(input = {}) {
|
|
|
416
524
|
});
|
|
417
525
|
}
|
|
418
526
|
s.stop('Discovery complete.');
|
|
527
|
+
if (previewLivenessUnknown) {
|
|
528
|
+
console.log(color.yellow('⚠ Preview liveness could not be verified — no preview log groups will be proposed. Check credentials (ECS) / AWS CLI (Lambda) and retry.'));
|
|
529
|
+
}
|
|
419
530
|
|
|
420
531
|
console.log(color.bold(`\nDry run — orphaned resources for project ${color.cyan(projectName)}:`));
|
|
421
532
|
printDiscovery(discovered);
|
|
@@ -472,6 +583,16 @@ async function runGcMain(input = {}) {
|
|
|
472
583
|
// Safety: only a literal `true` from the interactive prompt proceeds.
|
|
473
584
|
// Anything else (false, undefined, cancelled symbol) aborts deletion.
|
|
474
585
|
// --yes (or any auto-approve flag) skips the prompt explicitly.
|
|
586
|
+
if (!shouldAutoApprove(options)) {
|
|
587
|
+
const refused = await refuseIfNonInteractive(options, {
|
|
588
|
+
message: `\n✖ gc needs confirmation before deleting orphaned resources.`,
|
|
589
|
+
hint: ' Re-run with --yes to delete non-interactively.\n',
|
|
590
|
+
event: 'gc_run',
|
|
591
|
+
telemetry: { projectName },
|
|
592
|
+
errorCode: 'GC_NON_INTERACTIVE',
|
|
593
|
+
});
|
|
594
|
+
if (refused) return refused;
|
|
595
|
+
}
|
|
475
596
|
const confirmed = shouldAutoApprove(options)
|
|
476
597
|
? true
|
|
477
598
|
: await confirm({ message: color.yellow(CONFIRM_MESSAGE), initialValue: false });
|
package/src/commands/init.js
CHANGED
|
@@ -38,7 +38,7 @@ import { getTargetDirectory, getProjectConfig, promptWorkerCommand, promptGitHub
|
|
|
38
38
|
import { resolveDjangoWsgi, handleRailsCI } from '../utils/frameworks.js';
|
|
39
39
|
import { parseDockerCompose, selectComposeWebService } from '../utils/dockerCompose.js';
|
|
40
40
|
import { getBaseRules, getCursorRules, injectManagedBlock } from '../utils/ai-rules.js';
|
|
41
|
-
import { readFileSafe, COMPUTE_TARGETS, resolveInitSuffix, readTerraformProjectName, readTerraformOidcTrust } from '../utils/resolvers.js';
|
|
41
|
+
import { readFileSafe, COMPUTE_TARGETS, resolveHeadless, resolveInitSuffix, readTerraformProjectName, readTerraformOidcTrust } from '../utils/resolvers.js';
|
|
42
42
|
import { readGitHubRepoFromRemote, isValidGitHubRepoSlug } from '../utils/git.js';
|
|
43
43
|
import { parseDomainTf } from '../utils/domains.js';
|
|
44
44
|
|
|
@@ -197,6 +197,27 @@ async function mainStackMain(input = {}) {
|
|
|
197
197
|
const explicitGitHubRepo = typeof initOptions.githubRepo === 'string' && initOptions.githubRepo.trim() !== ''
|
|
198
198
|
? initOptions.githubRepo.trim()
|
|
199
199
|
: null;
|
|
200
|
+
// Non-interactive wizard gate (sync-ai precedent: bespoke, not the
|
|
201
|
+
// shared helper — approval flags cannot answer input questions, so
|
|
202
|
+
// even `init --yes` must refuse here). Without --headless the wizard
|
|
203
|
+
// always prompts (directory first), so an inferred-headless run (CI,
|
|
204
|
+
// no TTY) could only abandon — refuse loudly instead. This sits
|
|
205
|
+
// before the 2b flag validation below because the directory prompt
|
|
206
|
+
// precedes it; re-running with --headless surfaces any specific
|
|
207
|
+
// INVALID_* error. No preconfigured exemption: the parser only
|
|
208
|
+
// exposes flag values in headless mode, so standalone
|
|
209
|
+
// --preconfigured would silently ignore --framework/--region.
|
|
210
|
+
if (!isHeadless && resolveHeadless(options)) {
|
|
211
|
+
return failCommand({
|
|
212
|
+
message: '\n✖ init needs an interactive terminal to gather project configuration.',
|
|
213
|
+
hint: ' Re-run with --headless --framework <id> --target <ecs|lambda|static> (plus --region/--with as needed), or run interactively in a terminal.\n',
|
|
214
|
+
event: 'project_provisioned',
|
|
215
|
+
telemetry: { projectName: explicitProjectName ?? path.basename(process.cwd()) },
|
|
216
|
+
errorCode: 'INIT_NON_INTERACTIVE',
|
|
217
|
+
reason: 'non-interactive',
|
|
218
|
+
exitCode: 1,
|
|
219
|
+
});
|
|
220
|
+
}
|
|
200
221
|
const dirConfig = await getTargetDirectory(isHeadless, headlessOptions, { projectName: explicitProjectName });
|
|
201
222
|
|
|
202
223
|
// Re-init over an existing tree keeps the tree's project name: after a
|
|
@@ -903,7 +924,7 @@ async function mainStackMain(input = {}) {
|
|
|
903
924
|
fsSync.writeFileSync(path.join(promptsDir, 'grada.prompt'), getBaseRules(aiContext));
|
|
904
925
|
}
|
|
905
926
|
if (config.aiAssistants.includes('windsurf')) {
|
|
906
|
-
injectManagedBlock(path.join(cwd, '.windsurfrules'), getBaseRules(aiContext),
|
|
927
|
+
injectManagedBlock(path.join(cwd, '.windsurfrules'), getBaseRules(aiContext), true);
|
|
907
928
|
}
|
|
908
929
|
if (config.aiAssistants.includes('copilot')) {
|
|
909
930
|
const copilotPath = path.join(cwd, '.github', 'copilot-instructions.md');
|
|
@@ -942,7 +963,7 @@ async function mainStackMain(input = {}) {
|
|
|
942
963
|
fsSync.writeFileSync(path.join(promptsDir, 'grada.prompt'), getBaseRules(aiContext));
|
|
943
964
|
}
|
|
944
965
|
if (fsSync.existsSync(path.join(cwd, '.windsurf')) || fsSync.existsSync(path.join(cwd, '.windsurfrules'))) {
|
|
945
|
-
injectManagedBlock(path.join(cwd, '.windsurfrules'), getBaseRules(aiContext),
|
|
966
|
+
injectManagedBlock(path.join(cwd, '.windsurfrules'), getBaseRules(aiContext), true);
|
|
946
967
|
}
|
|
947
968
|
|
|
948
969
|
const copilotPath = path.join(cwd, '.github', 'copilot-instructions.md');
|