Skip to content

Commit bde9a77

Browse files
jariy17jariy17
andauthored
feat(project): sync vended CDK dependencies on build and deploy (#2861)
* feat(project): sync vended CDK dependencies on build and deploy agentcore create is the only writer of agentcore/cdk/package.json, so a project kept the @aws/agentcore-cdk it was created with across CLI upgrades. Fields a newer CLI writes to agentcore.json that the old library does not know were dropped at synth without an error. Before synth, build and deploy now rewrite every dependency the vended package.json names to the specifier this CLI vends and run npm install, leaving dependencies the user added alone. A pin newer than this CLI fails with an upgrade hint, non-version specifiers are skipped with a warning, and a failed install restores package.json. A deploy that removes the stack only warns. Opt out with 'agentcore config disableDependencyManagement true'. Ports the v0 behavior from #1777. * feat(project): install CDK dependencies when node_modules is missing When agentcore/cdk/node_modules is missing, build and deploy now run npm install in agentcore/cdk before synth (and before any AWS mutation on deploy), even when the pins already match, instead of failing with "Run 'npm install'". A failed install raises a ProjectStateError that names the directory and carries npm's error; a teardown only warns. With disableDependencyManagement set, the existing error is kept. * fix(project): explain that CLI-managed CDK dependencies can't be upgraded A newer @aws/agentcore-cdk now points at 'agentcore update'. A newer toolchain pin lists every CDK dependency the CLI manages, read from the vended package.json, and says to set it back or opt out with disableDependencyManagement. Blocking behavior is unchanged. * refactor(project): reuse declaresNothingDeployable and tidy CDK dependency sync Move declaresNothingDeployable to src/core/project/spec.ts so the CDK backend uses it to decide whether a dependency problem only warns, in place of its own inline check. Warn when package.json cannot be restored after a failed install, run npm install with --no-audit --no-fund as migrate does, correct the writers named in the sync's doc comment, and stop exporting types nothing else uses. Add tests that the build and deploy handlers and screens pass disableDependencyManagement to the backend. * refactor(project): simplify CDK dependency sync types and test setup parseSpecifier returns the base version and isNewer takes whether the vended pin is exact, since only that distinction was ever read. BuildBackendInput duplicated BuildProjectInput and is removed. The build and deploy handler tests seed the global config with applyOverrides. * test(project): drop CDK dependency sync tests covered by the backend suite * fix(project): decide CDK dependency installs from what is installed Address review feedback on the CDK dependency sync: - Install when the installed @aws/agentcore-cdk is missing or does not satisfy the declared pin, so a pulled manifest or an interrupted install no longer leaves a stale library. The restore-on-failure path is gone and npm's ProcessFailedError propagates unwrapped. - Leave a tilde or caret pin alone when major.minor match and its patch is at or above the vended one, so two CLI releases do not flip it. - With dependency management disabled, skip the newer-pin warning and warn about an older L3 pin instead. - Compare against the version this CLI vends, name both 'agentcore update' and the opt-out, give one sentence per newer pin, and show only the L3 pin when it is newer. - Validate the manifest with zod through ReadWriteJson so a malformed shape is a ProjectStateError, share the specifier parse with declaredCdkDependency, and keep the file's indent and line endings. * docs(readme): explain CDK dependency management on build and deploy --------- Co-authored-by: jariy17 <tjariy+jariy17@users.noreply.github.com>
1 parent 175e605 commit bde9a77

21 files changed

Lines changed: 929 additions & 87 deletions

‎README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,12 @@ Global flags, available on every command:
149149
(`transformAgentCoreJson`). All three come from `@aws/agentcore-cdk`, so that
150150
logic is updated through the library rather than changes to your CDK app.
151151

152+
`agentcore build` and `agentcore deploy` keep the dependencies `agentcore create`
153+
wrote to `agentcore/cdk/package.json` at the versions this CLI vends, and run
154+
`npm install` when they change or are not installed, so both commands may need
155+
network access to npm. Dependencies you add yourself are left alone. To manage
156+
the CDK dependencies yourself, run `agentcore config disableDependencyManagement true`.
157+
152158
`lib/cdk-stack.ts` instantiates one `AgentCoreApplication`. This is the file you
153159
edit to add your own resources. Runtimes and harnesses implement `iam.IGrantable`,
154160
so you can pass them to a resource's CDK grant methods to give your agents access.

‎src/core/project/backends/cdk.test.ts‎

Lines changed: 90 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { afterEach, describe, expect, spyOn, test } from "bun:test";
22
import * as fs from "node:fs";
3-
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3+
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
44
import { dirname, join, resolve } from "node:path";
55
import { tmpdir } from "node:os";
66
import type { Stack } from "@aws-sdk/client-cloudformation";
@@ -36,6 +36,7 @@ const OLD_PAYMENT_ARN =
3636
"arn:aws:bedrock-agentcore:us-east-1:111122223333:" +
3737
`token-vault/default/paymentcredentialprovider/${OLD_PAYMENT_PROVIDER}`;
3838
const json = new FsReadWriteJson({ logger: createSilentLogger() });
39+
const VENDED_CDK_PACKAGE_JSON = join(import.meta.dir, "../../../assets/cdk/package.json");
3940

4041
/** A template holding only what CDK adds itself, as an empty project synthesizes. */
4142
const METADATA_ONLY = { CDKMetadata: { Type: "AWS::CDK::Metadata" } };
@@ -574,6 +575,46 @@ describe("CdkBackend.build", () => {
574575
]);
575576
});
576577

578+
test("syncs the project's CDK dependencies to the vended pins before synthesizing", async () => {
579+
const input = await project();
580+
const vended = JSON.parse(await readFile(VENDED_CDK_PACKAGE_JSON, "utf8"));
581+
const manifestPath = join(cdkDirectory(input), "package.json");
582+
await writeFile(
583+
manifestPath,
584+
JSON.stringify({
585+
...vended,
586+
dependencies: { ...vended.dependencies, "@aws/agentcore-cdk": "1.0.3", zod: "4.1.0" },
587+
}),
588+
);
589+
const subject = harness();
590+
591+
const events = await collect(subject.backend.build(input));
592+
593+
const updated = JSON.parse(await readFile(manifestPath, "utf8"));
594+
expect(updated.dependencies).toEqual({ ...vended.dependencies, zod: "4.1.0" });
595+
expect(events[0]).toEqual({
596+
type: "step",
597+
message: `updating CDK dependencies: @aws/agentcore-cdk 1.0.3 -> ${vended.dependencies["@aws/agentcore-cdk"]}`,
598+
});
599+
expect(subject.commands).toEqual([
600+
{ command: ["npm", "install", "--no-audit", "--no-fund"], cwd: cdkDirectory(input) },
601+
{ command: synthCommand(input), cwd: cdkDirectory(input) },
602+
]);
603+
});
604+
605+
test("leaves the CDK dependencies alone when dependency management is disabled", async () => {
606+
const input = await project();
607+
const manifest = JSON.stringify({ dependencies: { "@aws/agentcore-cdk": "1.0.3" } });
608+
const manifestPath = join(cdkDirectory(input), "package.json");
609+
await writeFile(manifestPath, manifest);
610+
const subject = harness();
611+
612+
await collect(subject.backend.build(input, { disableDependencyManagement: true }));
613+
614+
expect(await readFile(manifestPath, "utf8")).toBe(manifest);
615+
expect(subject.commands).toEqual([{ command: synthCommand(input), cwd: cdkDirectory(input) }]);
616+
});
617+
577618
test("fails actionably when CDK dependencies are missing", async () => {
578619
const input = await project(false);
579620
const subject = harness();
@@ -1441,6 +1482,30 @@ describe("CdkBackend.deploy", () => {
14411482
expect(state.targets.default?.stackArn).toBeUndefined();
14421483
});
14431484

1485+
test("installs a missing node_modules before provisioning credentials", async () => {
1486+
const input = await project(false);
1487+
await writeFile(
1488+
join(cdkDirectory(input), "package.json"),
1489+
await readFile(VENDED_CDK_PACKAGE_JSON, "utf8"),
1490+
);
1491+
await writeAssembly(input, [TARGET.name]);
1492+
let commandsBeforeProvisioning: string[] = [];
1493+
// eslint-disable-next-line require-yield -- a spy that only records when provisioning starts
1494+
const provisionCredentials: CredentialProvisioner = async function* () {
1495+
commandsBeforeProvisioning = subject.commands.map(({ command }) => command.join(" "));
1496+
return {};
1497+
};
1498+
const subject = harness({ provisionCredentials });
1499+
1500+
const deployed = await collectDeploy(subject.backend.deploy(input, deployInput()));
1501+
1502+
expect(deployed.events).toContainEqual({
1503+
type: "step",
1504+
message: "installing CDK dependencies (node_modules missing)",
1505+
});
1506+
expect(commandsBeforeProvisioning).toEqual(["npm install --no-audit --no-fund"]);
1507+
});
1508+
14441509
test("checks local CDK prerequisites before provisioning credentials", async () => {
14451510
const input = await project(false); // no agentcore/cdk/node_modules
14461511
let provisioned = false;
@@ -1613,6 +1678,30 @@ describe("CdkBackend.deploy", () => {
16131678
expect(subject.transactionSearchRegions).toEqual([]);
16141679
});
16151680

1681+
test("does not block a teardown on a CDK pin newer than this CLI", async () => {
1682+
const input = await project();
1683+
await writeAssembly(input, [TARGET.name], { resources: METADATA_ONLY });
1684+
const vended = JSON.parse(await readFile(VENDED_CDK_PACKAGE_JSON, "utf8"));
1685+
await writeFile(
1686+
join(cdkDirectory(input), "package.json"),
1687+
JSON.stringify({
1688+
...vended,
1689+
dependencies: { ...vended.dependencies, "@aws/agentcore-cdk": "999.0.0" },
1690+
}),
1691+
);
1692+
const subject = harness();
1693+
1694+
const deployed = await collectDeploy(
1695+
subject.backend.deploy(input, deployInput({ confirmTeardown: async () => true })),
1696+
);
1697+
1698+
expect(deployed.result).toEqual({ outputs: {}, tornDown: true });
1699+
expect(deployed.events).toContainEqual({
1700+
type: "warning",
1701+
message: expect.stringContaining("@aws/agentcore-cdk 999.0.0"),
1702+
});
1703+
});
1704+
16161705
test("removes the stack when the teardown is confirmed", async () => {
16171706
const input = await project();
16181707
await writeAssembly(input, [TARGET.name], { resources: METADATA_ONLY });

‎src/core/project/backends/cdk.ts‎

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { GetTemplateCommand, type Stack } from "@aws-sdk/client-cloudformation";
44
import { parse as parseYaml } from "yaml";
55
import { MalformedServiceResponseError, ProjectStateError } from "../../../errors/errors";
66
import type {
7+
BuildProjectInput,
78
DeployResult,
89
Project,
910
ProjectEvent,
@@ -25,6 +26,9 @@ import {
2526
import { buildxDriverWarning, checkArm64Builder, selectBuildxBuilder } from "./cdk/arm64Builder";
2627
import { localImageBuilds } from "./cdk/localImages";
2728
import { resolveCdkDockerExecutable } from "../../dev/containerTool";
29+
import { syncCdkDependencies } from "./cdk/dependencies";
30+
import { declaresNothingDeployable } from "../spec";
31+
import { defaultSource, type AssetSource } from "../source";
2832
import {
2933
createLineSplitter,
3034
FsReadWriteJson,
@@ -151,6 +155,8 @@ export type CdkBackendConfig = {
151155
runner?: ProcessRunner;
152156
checkTool?: typeof requireTool;
153157
json?: ReadWriteJson;
158+
/** Where the CDK package.json this CLI vends is read from, as the pins to sync to. */
159+
source?: AssetSource;
154160
createCloudFormationClient?: CreateCloudFormationClient;
155161
/** Identity client used to provision the project's credential providers. */
156162
identity: CredentialProviderCalls;
@@ -192,6 +198,7 @@ export class CdkBackend implements ProjectBackend {
192198
private readonly runner: ProcessRunner;
193199
private readonly checkTool: typeof requireTool;
194200
private readonly json: ReadWriteJson;
201+
private readonly source: AssetSource;
195202
private readonly cdk: CdkRunner;
196203
private readonly resolveCredentials: CdkCredentialResolver;
197204
private readonly bootstrap: BootstrapProbe;
@@ -218,6 +225,7 @@ export class CdkBackend implements ProjectBackend {
218225
config.createCloudFormationClient ?? createCloudFormationClient;
219226
this.checkTool = config.checkTool ?? requireTool;
220227
this.json = config.json ?? new FsReadWriteJson({ logger: config.logger });
228+
this.source = config.source ?? defaultSource();
221229
this.cdk = config.cdk ?? createCdkRunner(config.logger);
222230
this.resolveCredentials =
223231
config.resolveCredentials ?? createCdkCredentialResolver(config.logger);
@@ -247,24 +255,39 @@ export class CdkBackend implements ProjectBackend {
247255

248256
// Local prerequisites for synth. Checked before any AWS mutation so a missing
249257
// toolchain or dependencies fails without having provisioned credentials.
250-
private async ensureCdkDependencies(project: Project): Promise<void> {
258+
private async *ensureCdkDependencies(
259+
project: Project,
260+
input: BuildProjectInput & { lenient?: boolean },
261+
): AsyncGenerator<ProjectEvent, void> {
251262
const cdkDir = this.cdkDirectory(project);
252-
if (!existsSync(join(cdkDir, "node_modules"))) {
263+
await this.checkTool("npm", "Install Node.js: https://nodejs.org/");
264+
// The sync installs a missing node_modules, unless the user manages dependencies
265+
// themselves or there is no package.json to install from.
266+
if (
267+
!existsSync(join(cdkDir, "node_modules")) &&
268+
(input.disableDependencyManagement || !existsSync(join(cdkDir, "package.json")))
269+
) {
253270
throw new ProjectStateError(
254271
`CDK dependencies are missing for project '${project.name}'. ` +
255272
`Run 'npm install' in ${cdkDir}.`,
256273
);
257274
}
258-
await this.checkTool("npm", "Install Node.js: https://nodejs.org/");
275+
yield* syncCdkDependencies({
276+
cdkDirectory: cdkDir,
277+
vendedManifest: await this.source.read("cdk/package.json"),
278+
json: this.json,
279+
runner: this.runner,
280+
logger: this.logger,
281+
disabled: input.disableDependencyManagement,
282+
lenient: input.lenient,
283+
});
259284
}
260285

261286
private async *synthesize(
262287
project: Project,
263288
explainUndeployedCredentials: boolean,
264289
builds: WorkloadBuilds,
265290
): AsyncGenerator<ProjectEvent, void> {
266-
await this.ensureCdkDependencies(project);
267-
268291
const compatibilityWarning = await cdkCompatibilityWarning(this.cdkDirectory(project));
269292
if (compatibilityWarning) {
270293
yield { type: "warning", message: compatibilityWarning };
@@ -302,7 +325,11 @@ export class CdkBackend implements ProjectBackend {
302325
}
303326
}
304327

305-
public async *build(project: Project): AsyncGenerator<ProjectEvent, void> {
328+
public async *build(
329+
project: Project,
330+
input: BuildProjectInput = {},
331+
): AsyncGenerator<ProjectEvent, void> {
332+
yield* this.ensureCdkDependencies(project, input);
306333
const { builds, local } = resolveWorkloads(project);
307334
yield* this.synthesize(project, true, builds);
308335
yield* this.buildLocalImages(project, builds, local);
@@ -375,7 +402,12 @@ export class CdkBackend implements ProjectBackend {
375402
// Fail on local setup errors (missing toolchain/deps) and malformed state
376403
// before any AWS mutation, so a local problem never leaves credentials
377404
// provisioned or the stack ARN unrecorded.
378-
await this.ensureCdkDependencies(project);
405+
// A project that declares nothing is about to have its stack removed, and a
406+
// dependency problem must not keep that from happening.
407+
yield* this.ensureCdkDependencies(project, {
408+
...input,
409+
lenient: declaresNothingDeployable(project),
410+
});
379411
const { builds, local } = input.workloadBuilds
380412
? { builds: input.workloadBuilds, local: input.localWorkloads ?? new Map() }
381413
: resolveWorkloads(project);

‎src/core/project/backends/cdk/compatibility.ts‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,21 +35,21 @@ export function assertCdkLocalContainerSupport(cdkDirectory: string): void {
3535
);
3636
}
3737

38-
export async function cdkCompatibilityWarning(cdkDirectory: string): Promise<string | undefined> {
38+
/** The `@aws/agentcore-cdk` version installed in `node_modules`, if it can be read. */
39+
export async function installedCdkVersion(cdkDirectory: string): Promise<string | undefined> {
3940
const packagePath = join(cdkDirectory, "node_modules", "@aws", "agentcore-cdk", "package.json");
40-
41-
let installedVersion: unknown;
4241
try {
43-
const packageJson = JSON.parse(await readFile(packagePath, "utf8")) as {
44-
version?: unknown;
45-
};
46-
installedVersion = packageJson.version;
42+
const { version } = JSON.parse(await readFile(packagePath, "utf8")) as { version?: unknown };
43+
return typeof version === "string" ? version : undefined;
4744
} catch {
4845
return undefined;
4946
}
47+
}
5048

49+
export async function cdkCompatibilityWarning(cdkDirectory: string): Promise<string | undefined> {
50+
const installedVersion = await installedCdkVersion(cdkDirectory);
5151
if (
52-
typeof installedVersion !== "string" ||
52+
installedVersion === undefined ||
5353
semver.valid(installedVersion) === null ||
5454
!semver.lt(installedVersion, MINIMUM_COMPATIBLE_CDK_VERSION)
5555
) {

0 commit comments

Comments
 (0)