Original file line numberDiff line numberDiff line change
Expand Up@@ -139,13 +139,13 @@ describe('setupHttpGateways', () => {

expect(mockCreateHttpGateway).toHaveBeenCalledWith({
region: 'us-east-1',
name: 'MyHttpGw',
name: 'TestProject-MyHttpGw',
roleArn: 'arn:aws:iam::123456789012:role/ExistingRole',
});
expect(mockCreateHttpGatewayTarget).toHaveBeenCalledWith({
region: 'us-east-1',
gatewayId: 'gw-001',
targetName: 'my-agent',
targetName: 'TestProject-my-agent',
runtimeArn: 'arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/rt-123',
});
});
Expand DownExpand Up@@ -175,7 +175,7 @@ describe('setupHttpGateways', () => {

it('finds gateway by name via list (state loss recovery)', async () => {
mockListAllHttpGateways.mockResolvedValue([
{ name: 'MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
{ name: 'TestProject-MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
]);

const result = await setupHttpGateways({
Expand All@@ -190,6 +190,39 @@ describe('setupHttpGateways', () => {
expect(mockCreateHttpGateway).not.toHaveBeenCalled();
});

it('recovers state using legacy (pre-migration) gateway name when prefixed name not found', async () => {
// First call: prefixed name "TestProject-MyHttpGw" → not found
// Second call: unprefixed legacy name "MyHttpGw" → found
mockListAllHttpGateways
.mockResolvedValueOnce([])
.mockResolvedValueOnce([{ name: 'MyHttpGw', gatewayId: 'gw-legacy', gatewayArn: 'arn:httpgw:legacy' }]);

const warnSpy = vi.spyOn(console, 'warn').mockReturnValue(undefined);

const result = await setupHttpGateways({
region: 'us-east-1',
projectName: 'TestProject',
projectSpec: makeProjectSpec([sampleHttpGateway]),
deployedResources: sampleDeployedResources,
});

// findHttpGatewayByName was called twice: once for prefixed, once for unprefixed name
expect(mockListAllHttpGateways).toHaveBeenCalledTimes(2);

// Gateway result is skipped (not created)
expect(result.results[0]!.status).toBe('skipped');
expect(result.results[0]!.gatewayId).toBe('gw-legacy');
expect(result.httpGateways.MyHttpGw!.gatewayId).toBe('gw-legacy');

// createHttpGateway was NOT called
expect(mockCreateHttpGateway).not.toHaveBeenCalled();

// console.warn was called with the pre-migration warning text
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('pre-migration name'));

warnSpy.mockRestore();
});

it('reports error on missing runtime ref', async () => {
const emptyDeployedResources = {} as unknown as DeployedResourceState;

Expand Down
45 changes: 45 additions & 0 deletions src/cli/operations/deploy/__tests__/preflight.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -126,6 +126,51 @@ describe('validateProject', () => {
expect(result.projectSpec.name).toBe('test-project');
expect(result.isTeardownDeploy).toBe(false);
});

it('rejects gateway target name that exceeds 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (39) = 49 > 48
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(39), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

await expect(validateProject()).rejects.toThrow(
'HTTP gateway target "' + 'a'.repeat(39) + '" in gateway "gw" would exceed the 48-character AWS limit'
);
});

it('accepts gateway target name within 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (38) = 48 == limit
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(38), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

const result = await validateProject();
expect(result.projectSpec.name).toBe('myproject');
});
});

describe('formatError', () => {
Expand Down
25 changes: 21 additions & 4 deletions src/cli/operations/deploy/post-deploy-ab-tests.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -142,7 +142,7 @@ export async function setupABTests(options: SetupABTestsOptions): Promise<SetupA
const existingTest = existingABTests?.[testSpec.name];

// Resolve ARN references from deployed state
const resolvedVariants = resolveVariants(testSpec.variants, deployedResources);
const resolvedVariants = resolveVariants(testSpec.variants, projectSpec.name, deployedResources);
Comment thread
jariy17 marked this conversation as resolved.
const resolvedGatewayArn = resolveGatewayArn(testSpec.gatewayRef, deployedResources);
if (!resolvedGatewayArn.startsWith('arn:') || resolvedGatewayArn.split(':').length < 6) {
results.push({
Expand DownExpand Up@@ -409,7 +409,8 @@ async function findABTestByName(
/**
* Resolve variant config bundle references.
* If bundleArn is a name (not an ARN), look it up in deployed config bundles.
* Target-based variants are passed through as-is.
* Target-based variants have their target name prefixed with projectName to match
* what post-deploy-http-gateways.ts creates on AWS (e.g. `${projectName}-${tgt.name}`).
Comment thread
jariy17 marked this conversation as resolved.
*/
function resolveVariants(
variants: {
Expand All@@ -420,6 +421,7 @@ function resolveVariants(
target?: { targetName: string };
};
}[],
projectName: string,
deployedResources?: DeployedResourceState
): ABTestVariant[] {
return variants.map(v => {
Expand All@@ -436,12 +438,15 @@ function resolveVariants(
},
};
}
// Target-based variant — pass through
// Target-based variant — prepend projectName to match the AWS-side name created by
// post-deploy-http-gateways.ts: `${projectName}-${tgt.name}`
return {
name: v.name,
weight: v.weight,
variantConfiguration: {
...(v.variantConfiguration.target && { target: { name: v.variantConfiguration.target.targetName } }),
...(v.variantConfiguration.target && {
target: { name: resolveTargetName(v.variantConfiguration.target.targetName, projectName) },
}),
},
};
});
Expand DownExpand Up@@ -475,6 +480,18 @@ function resolveConfigBundleVersion(
return versionRef;
}

/**
* Resolve a variant target name, applying the project prefix if not already present.
* This handles legacy configs that were created before the prefix requirement.
*/
function resolveTargetName(targetName: string, projectName: string): string {
// If the target name already starts with the project prefix, use as-is to avoid double-prefixing
if (targetName.startsWith(`${projectName}-`)) {
return targetName;
}
return `${projectName}-${targetName}`;
}

function resolveGatewayArn(ref: string, deployedResources?: DeployedResourceState): string {
if (ref.startsWith('arn:')) return ref;

Expand Down
36 changes: 30 additions & 6 deletions src/cli/operations/deploy/post-deploy-http-gateways.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

for (const tgt of gwSpec.targets) {
const existingTarget = existingTargetsByName.get(tgt.name);
const existingTarget = existingTargetsByName.get(`${projectName}-${tgt.name}`);
if (existingTarget) {
// Target exists by name — check if qualifier matches
try {
Expand DownExpand Up@@ -143,7 +143,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: existingGateway.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand All@@ -170,7 +170,8 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

// Try to find by name via list (handles re-creation after state loss)
const existingByName = await findHttpGatewayByName(region, gwSpec.name);
const prefixedGatewayName = `${projectName}-${gwSpec.name}`;
const existingByName = await findHttpGatewayByName(region, prefixedGatewayName);
if (existingByName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" found by name but local state was lost. Target and role state may be incomplete — consider re-deploying.`
Expand All@@ -189,6 +190,29 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
continue;
}

// Migration fallback: try unprefixed name for pre-PR gateways (Comment 3 fix)
const existingByLegacyName = await findHttpGatewayByName(region, gwSpec.name);
if (existingByLegacyName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" was found using its pre-migration name. ` +
`This CLI version uses the naming convention "${prefixedGatewayName}". ` +
`The gateway has been recovered from state loss. ` +
`You may want to rename "${gwSpec.name}" to "${prefixedGatewayName}" on AWS to match the new convention.`
);
httpGateways[gwSpec.name] = {
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
// targetId, roleArn, roleCreatedByCli unknown after state-loss recovery
};
results.push({
gatewayName: gwSpec.name,
status: 'skipped',
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
});
continue;
}

// Resolve runtime ARN from deployed state
const runtimeState = deployedResources?.runtimes?.[gwSpec.runtimeRef];
if (!runtimeState) {
Expand DownExpand Up@@ -216,7 +240,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
// Creating HTTP gateway for runtime
const createResult = await createHttpGateway({
region,
name: gwSpec.name,
name: `${projectName}-${gwSpec.name}`,
roleArn: resolvedRoleArn,
});

Expand All@@ -231,7 +255,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const targetResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: gwSpec.runtimeRef,
targetName: `${projectName}-${gwSpec.runtimeRef}`,
runtimeArn,
});

Expand DownExpand Up@@ -288,7 +312,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand Down
34 changes: 34 additions & 0 deletions src/cli/operations/deploy/preflight.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ export function formatError(err: unknown): string {
* Returns the project context needed for subsequent steps.
*/
const MAX_RUNTIME_NAME_LENGTH = 48;
const MAX_GATEWAY_COMBINED_NAME_LENGTH = 48;

export async function validateProject(): Promise<PreflightContext> {
// Find the agentcore config directory, walking up from cwd if needed
Expand DownExpand Up@@ -108,6 +109,9 @@ export async function validateProject(): Promise<PreflightContext> {
// Validate runtime names don't exceed AWS limits
validateRuntimeNames(projectSpec);

// Validate HTTP gateway names don't exceed AWS limits when combined with project name
validateHttpGatewayNames(projectSpec);

// Validate Container agents have Dockerfiles
validateContainerAgents(projectSpec, configRoot);

Expand DownExpand Up@@ -140,6 +144,36 @@ function validateRuntimeNames(projectSpec: AgentCoreProjectSpec): void {
}
}

/**
* Validates that combined HTTP gateway names (projectName-gatewayName) don't exceed AWS limits.
*/
function validateHttpGatewayNames(projectSpec: AgentCoreProjectSpec): void {
const projectName = projectSpec.name;
for (const gateway of projectSpec.httpGateways ?? []) {
const gwName = gateway.name;
if (gwName) {
const combinedName = `${projectName}-${gwName}`;
if (combinedName.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
throw new Error(
`HTTP gateway name too long: "${combinedName}" (${combinedName.length} chars). ` +
`AWS limits gateway names to ${MAX_GATEWAY_COMBINED_NAME_LENGTH} characters. ` +
`Shorten the project name or gateway name in agentcore.json.`
);
}
}
for (const target of gateway.targets ?? []) {
const combined = `${projectName}-${target.name}`;
if (combined.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
const maxTargetLen = MAX_GATEWAY_COMBINED_NAME_LENGTH - projectName.length - 1;
throw new Error(
`HTTP gateway target "${target.name}" in gateway "${gwName}" would exceed the ${MAX_GATEWAY_COMBINED_NAME_LENGTH}-character AWS limit when prefixed with project name "${projectName}-" (total: ${combined.length} chars). ` +
`Shorten the target name to ${maxTargetLen} characters or fewer.`
);
}
}
}
}

/**
* Validates that Container agents have required Dockerfiles.
*/
Expand Down
12 changes: 6 additions & 6 deletions src/schema/schemas/primitives/__tests__/http-gateway.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,12 +22,12 @@ describe('HttpGatewayNameSchema', () => {
expect(HttpGatewayNameSchema.safeParse('my_gateway').success).toBe(false);
});

it('rejects name over 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(49)).success).toBe(false);
it('accepts name longer than 24 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(25)).success).toBe(true);
});

it('accepts name at 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(48)).success).toBe(true);
it('accepts name at 47 chars (room for 1-char project name + hyphen)', () => {
expect(HttpGatewayNameSchema.safeParse('a' + 'b'.repeat(46)).success).toBe(true);
});
});

Expand DownExpand Up@@ -60,8 +60,8 @@ describe('HttpGatewaySchema', () => {
expect(HttpGatewaySchema.safeParse(withoutRuntimeRef).success).toBe(false);
});

it('rejects name too long (>48 chars)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a'.repeat(49) }).success).toBe(false);
it('accepts name longer than 24 chars (no standalone max cap)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a' + 'b'.repeat(30) }).success).toBe(true);
});

it('rejects name starting with number', () => {
Expand Down
5 changes: 2 additions & 3 deletions src/schema/schemas/primitives/http-gateway.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,9 @@ import { z } from 'zod';
export const HttpGatewayNameSchema = z
.string()
.min(1, 'Name is required')
.max(48)
.regex(
/^[a-zA-Z][a-zA-Z0-9-]{0,47}$/,
'Must begin with a letter and contain only alphanumeric characters and hyphens (max 48 chars)'
Comment thread
jariy17 marked this conversation as resolved.
/^[a-zA-Z][a-zA-Z0-9-]*$/,
'Gateway name must start with a letter and contain only alphanumeric characters or hyphens (combined with project name must fit 48-char AWS limit)'
);

export const HttpGatewayTargetSchema = z.object({
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,13 +139,13 @@ describe('setupHttpGateways', () => {

expect(mockCreateHttpGateway).toHaveBeenCalledWith({
region: 'us-east-1',
name: 'MyHttpGw',
name: 'TestProject-MyHttpGw',
roleArn: 'arn:aws:iam::123456789012:role/ExistingRole',
});
expect(mockCreateHttpGatewayTarget).toHaveBeenCalledWith({
region: 'us-east-1',
gatewayId: 'gw-001',
targetName: 'my-agent',
targetName: 'TestProject-my-agent',
runtimeArn: 'arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/rt-123',
});
});
Expand DownExpand Up@@ -175,7 +175,7 @@ describe('setupHttpGateways', () => {

it('finds gateway by name via list (state loss recovery)', async () => {
mockListAllHttpGateways.mockResolvedValue([
{ name: 'MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
{ name: 'TestProject-MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
]);

const result = await setupHttpGateways({
Expand All@@ -190,6 +190,39 @@ describe('setupHttpGateways', () => {
expect(mockCreateHttpGateway).not.toHaveBeenCalled();
});

it('recovers state using legacy (pre-migration) gateway name when prefixed name not found', async () => {
// First call: prefixed name "TestProject-MyHttpGw" → not found
// Second call: unprefixed legacy name "MyHttpGw" → found
mockListAllHttpGateways
.mockResolvedValueOnce([])
.mockResolvedValueOnce([{ name: 'MyHttpGw', gatewayId: 'gw-legacy', gatewayArn: 'arn:httpgw:legacy' }]);

const warnSpy = vi.spyOn(console, 'warn').mockReturnValue(undefined);

const result = await setupHttpGateways({
region: 'us-east-1',
projectName: 'TestProject',
projectSpec: makeProjectSpec([sampleHttpGateway]),
deployedResources: sampleDeployedResources,
});

// findHttpGatewayByName was called twice: once for prefixed, once for unprefixed name
expect(mockListAllHttpGateways).toHaveBeenCalledTimes(2);

// Gateway result is skipped (not created)
expect(result.results[0]!.status).toBe('skipped');
expect(result.results[0]!.gatewayId).toBe('gw-legacy');
expect(result.httpGateways.MyHttpGw!.gatewayId).toBe('gw-legacy');

// createHttpGateway was NOT called
expect(mockCreateHttpGateway).not.toHaveBeenCalled();

// console.warn was called with the pre-migration warning text
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('pre-migration name'));

warnSpy.mockRestore();
});

it('reports error on missing runtime ref', async () => {
const emptyDeployedResources = {} as unknown as DeployedResourceState;

Expand Down
45 changes: 45 additions & 0 deletions src/cli/operations/deploy/__tests__/preflight.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -126,6 +126,51 @@ describe('validateProject', () => {
expect(result.projectSpec.name).toBe('test-project');
expect(result.isTeardownDeploy).toBe(false);
});

it('rejects gateway target name that exceeds 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (39) = 49 > 48
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(39), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

await expect(validateProject()).rejects.toThrow(
'HTTP gateway target "' + 'a'.repeat(39) + '" in gateway "gw" would exceed the 48-character AWS limit'
);
});

it('accepts gateway target name within 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (38) = 48 == limit
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(38), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

const result = await validateProject();
expect(result.projectSpec.name).toBe('myproject');
});
});

describe('formatError', () => {
Expand Down
25 changes: 21 additions & 4 deletions src/cli/operations/deploy/post-deploy-ab-tests.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -142,7 +142,7 @@ export async function setupABTests(options: SetupABTestsOptions): Promise<SetupA
const existingTest = existingABTests?.[testSpec.name];

// Resolve ARN references from deployed state
const resolvedVariants = resolveVariants(testSpec.variants, deployedResources);
const resolvedVariants = resolveVariants(testSpec.variants, projectSpec.name, deployedResources);
Comment thread
jariy17 marked this conversation as resolved.
const resolvedGatewayArn = resolveGatewayArn(testSpec.gatewayRef, deployedResources);
if (!resolvedGatewayArn.startsWith('arn:') || resolvedGatewayArn.split(':').length < 6) {
results.push({
Expand DownExpand Up@@ -409,7 +409,8 @@ async function findABTestByName(
/**
* Resolve variant config bundle references.
* If bundleArn is a name (not an ARN), look it up in deployed config bundles.
* Target-based variants are passed through as-is.
* Target-based variants have their target name prefixed with projectName to match
* what post-deploy-http-gateways.ts creates on AWS (e.g. `${projectName}-${tgt.name}`).
Comment thread
jariy17 marked this conversation as resolved.
*/
function resolveVariants(
variants: {
Expand All@@ -420,6 +421,7 @@ function resolveVariants(
target?: { targetName: string };
};
}[],
projectName: string,
deployedResources?: DeployedResourceState
): ABTestVariant[] {
return variants.map(v => {
Expand All@@ -436,12 +438,15 @@ function resolveVariants(
},
};
}
// Target-based variant — pass through
// Target-based variant — prepend projectName to match the AWS-side name created by
// post-deploy-http-gateways.ts: `${projectName}-${tgt.name}`
return {
name: v.name,
weight: v.weight,
variantConfiguration: {
...(v.variantConfiguration.target && { target: { name: v.variantConfiguration.target.targetName } }),
...(v.variantConfiguration.target && {
target: { name: resolveTargetName(v.variantConfiguration.target.targetName, projectName) },
}),
},
};
});
Expand DownExpand Up@@ -475,6 +480,18 @@ function resolveConfigBundleVersion(
return versionRef;
}

/**
* Resolve a variant target name, applying the project prefix if not already present.
* This handles legacy configs that were created before the prefix requirement.
*/
function resolveTargetName(targetName: string, projectName: string): string {
// If the target name already starts with the project prefix, use as-is to avoid double-prefixing
if (targetName.startsWith(`${projectName}-`)) {
return targetName;
}
return `${projectName}-${targetName}`;
}

function resolveGatewayArn(ref: string, deployedResources?: DeployedResourceState): string {
if (ref.startsWith('arn:')) return ref;

Expand Down
36 changes: 30 additions & 6 deletions src/cli/operations/deploy/post-deploy-http-gateways.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

for (const tgt of gwSpec.targets) {
const existingTarget = existingTargetsByName.get(tgt.name);
const existingTarget = existingTargetsByName.get(`${projectName}-${tgt.name}`);
if (existingTarget) {
// Target exists by name — check if qualifier matches
try {
Expand DownExpand Up@@ -143,7 +143,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: existingGateway.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand All@@ -170,7 +170,8 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

// Try to find by name via list (handles re-creation after state loss)
const existingByName = await findHttpGatewayByName(region, gwSpec.name);
const prefixedGatewayName = `${projectName}-${gwSpec.name}`;
const existingByName = await findHttpGatewayByName(region, prefixedGatewayName);
if (existingByName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" found by name but local state was lost. Target and role state may be incomplete — consider re-deploying.`
Expand All@@ -189,6 +190,29 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
continue;
}

// Migration fallback: try unprefixed name for pre-PR gateways (Comment 3 fix)
const existingByLegacyName = await findHttpGatewayByName(region, gwSpec.name);
if (existingByLegacyName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" was found using its pre-migration name. ` +
`This CLI version uses the naming convention "${prefixedGatewayName}". ` +
`The gateway has been recovered from state loss. ` +
`You may want to rename "${gwSpec.name}" to "${prefixedGatewayName}" on AWS to match the new convention.`
);
httpGateways[gwSpec.name] = {
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
// targetId, roleArn, roleCreatedByCli unknown after state-loss recovery
};
results.push({
gatewayName: gwSpec.name,
status: 'skipped',
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
});
continue;
}

// Resolve runtime ARN from deployed state
const runtimeState = deployedResources?.runtimes?.[gwSpec.runtimeRef];
if (!runtimeState) {
Expand DownExpand Up@@ -216,7 +240,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
// Creating HTTP gateway for runtime
const createResult = await createHttpGateway({
region,
name: gwSpec.name,
name: `${projectName}-${gwSpec.name}`,
roleArn: resolvedRoleArn,
});

Expand All@@ -231,7 +255,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const targetResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: gwSpec.runtimeRef,
targetName: `${projectName}-${gwSpec.runtimeRef}`,
runtimeArn,
});

Expand DownExpand Up@@ -288,7 +312,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand Down
34 changes: 34 additions & 0 deletions src/cli/operations/deploy/preflight.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ export function formatError(err: unknown): string {
* Returns the project context needed for subsequent steps.
*/
const MAX_RUNTIME_NAME_LENGTH = 48;
const MAX_GATEWAY_COMBINED_NAME_LENGTH = 48;

export async function validateProject(): Promise<PreflightContext> {
// Find the agentcore config directory, walking up from cwd if needed
Expand DownExpand Up@@ -108,6 +109,9 @@ export async function validateProject(): Promise<PreflightContext> {
// Validate runtime names don't exceed AWS limits
validateRuntimeNames(projectSpec);

// Validate HTTP gateway names don't exceed AWS limits when combined with project name
validateHttpGatewayNames(projectSpec);

// Validate Container agents have Dockerfiles
validateContainerAgents(projectSpec, configRoot);

Expand DownExpand Up@@ -140,6 +144,36 @@ function validateRuntimeNames(projectSpec: AgentCoreProjectSpec): void {
}
}

/**
* Validates that combined HTTP gateway names (projectName-gatewayName) don't exceed AWS limits.
*/
function validateHttpGatewayNames(projectSpec: AgentCoreProjectSpec): void {
const projectName = projectSpec.name;
for (const gateway of projectSpec.httpGateways ?? []) {
const gwName = gateway.name;
if (gwName) {
const combinedName = `${projectName}-${gwName}`;
if (combinedName.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
throw new Error(
`HTTP gateway name too long: "${combinedName}" (${combinedName.length} chars). ` +
`AWS limits gateway names to ${MAX_GATEWAY_COMBINED_NAME_LENGTH} characters. ` +
`Shorten the project name or gateway name in agentcore.json.`
);
}
}
for (const target of gateway.targets ?? []) {
const combined = `${projectName}-${target.name}`;
if (combined.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
const maxTargetLen = MAX_GATEWAY_COMBINED_NAME_LENGTH - projectName.length - 1;
throw new Error(
`HTTP gateway target "${target.name}" in gateway "${gwName}" would exceed the ${MAX_GATEWAY_COMBINED_NAME_LENGTH}-character AWS limit when prefixed with project name "${projectName}-" (total: ${combined.length} chars). ` +
`Shorten the target name to ${maxTargetLen} characters or fewer.`
);
}
}
}
}

/**
* Validates that Container agents have required Dockerfiles.
*/
Expand Down
12 changes: 6 additions & 6 deletions src/schema/schemas/primitives/__tests__/http-gateway.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,12 +22,12 @@ describe('HttpGatewayNameSchema', () => {
expect(HttpGatewayNameSchema.safeParse('my_gateway').success).toBe(false);
});

it('rejects name over 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(49)).success).toBe(false);
it('accepts name longer than 24 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(25)).success).toBe(true);
});

it('accepts name at 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(48)).success).toBe(true);
it('accepts name at 47 chars (room for 1-char project name + hyphen)', () => {
expect(HttpGatewayNameSchema.safeParse('a' + 'b'.repeat(46)).success).toBe(true);
});
});

Expand DownExpand Up@@ -60,8 +60,8 @@ describe('HttpGatewaySchema', () => {
expect(HttpGatewaySchema.safeParse(withoutRuntimeRef).success).toBe(false);
});

it('rejects name too long (>48 chars)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a'.repeat(49) }).success).toBe(false);
it('accepts name longer than 24 chars (no standalone max cap)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a' + 'b'.repeat(30) }).success).toBe(true);
});

it('rejects name starting with number', () => {
Expand Down
5 changes: 2 additions & 3 deletions src/schema/schemas/primitives/http-gateway.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,9 @@ import { z } from 'zod';
export const HttpGatewayNameSchema = z
.string()
.min(1, 'Name is required')
.max(48)
.regex(
/^[a-zA-Z][a-zA-Z0-9-]{0,47}$/,
'Must begin with a letter and contain only alphanumeric characters and hyphens (max 48 chars)'
Comment thread
jariy17 marked this conversation as resolved.
/^[a-zA-Z][a-zA-Z0-9-]*$/,
'Gateway name must start with a letter and contain only alphanumeric characters or hyphens (combined with project name must fit 48-char AWS limit)'
);

export const HttpGatewayTargetSchema = z.object({
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,13 +139,13 @@ describe('setupHttpGateways', () => {

expect(mockCreateHttpGateway).toHaveBeenCalledWith({
region: 'us-east-1',
name: 'MyHttpGw',
name: 'TestProject-MyHttpGw',
roleArn: 'arn:aws:iam::123456789012:role/ExistingRole',
});
expect(mockCreateHttpGatewayTarget).toHaveBeenCalledWith({
region: 'us-east-1',
gatewayId: 'gw-001',
targetName: 'my-agent',
targetName: 'TestProject-my-agent',
runtimeArn: 'arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/rt-123',
});
});
Expand DownExpand Up@@ -175,7 +175,7 @@ describe('setupHttpGateways', () => {

it('finds gateway by name via list (state loss recovery)', async () => {
mockListAllHttpGateways.mockResolvedValue([
{ name: 'MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
{ name: 'TestProject-MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
]);

const result = await setupHttpGateways({
Expand All@@ -190,6 +190,39 @@ describe('setupHttpGateways', () => {
expect(mockCreateHttpGateway).not.toHaveBeenCalled();
});

it('recovers state using legacy (pre-migration) gateway name when prefixed name not found', async () => {
// First call: prefixed name "TestProject-MyHttpGw" → not found
// Second call: unprefixed legacy name "MyHttpGw" → found
mockListAllHttpGateways
.mockResolvedValueOnce([])
.mockResolvedValueOnce([{ name: 'MyHttpGw', gatewayId: 'gw-legacy', gatewayArn: 'arn:httpgw:legacy' }]);

const warnSpy = vi.spyOn(console, 'warn').mockReturnValue(undefined);

const result = await setupHttpGateways({
region: 'us-east-1',
projectName: 'TestProject',
projectSpec: makeProjectSpec([sampleHttpGateway]),
deployedResources: sampleDeployedResources,
});

// findHttpGatewayByName was called twice: once for prefixed, once for unprefixed name
expect(mockListAllHttpGateways).toHaveBeenCalledTimes(2);

// Gateway result is skipped (not created)
expect(result.results[0]!.status).toBe('skipped');
expect(result.results[0]!.gatewayId).toBe('gw-legacy');
expect(result.httpGateways.MyHttpGw!.gatewayId).toBe('gw-legacy');

// createHttpGateway was NOT called
expect(mockCreateHttpGateway).not.toHaveBeenCalled();

// console.warn was called with the pre-migration warning text
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('pre-migration name'));

warnSpy.mockRestore();
});

it('reports error on missing runtime ref', async () => {
const emptyDeployedResources = {} as unknown as DeployedResourceState;

Expand Down
45 changes: 45 additions & 0 deletions src/cli/operations/deploy/__tests__/preflight.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -126,6 +126,51 @@ describe('validateProject', () => {
expect(result.projectSpec.name).toBe('test-project');
expect(result.isTeardownDeploy).toBe(false);
});

it('rejects gateway target name that exceeds 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (39) = 49 > 48
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(39), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

await expect(validateProject()).rejects.toThrow(
'HTTP gateway target "' + 'a'.repeat(39) + '" in gateway "gw" would exceed the 48-character AWS limit'
);
});

it('accepts gateway target name within 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (38) = 48 == limit
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(38), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

const result = await validateProject();
expect(result.projectSpec.name).toBe('myproject');
});
});

describe('formatError', () => {
Expand Down
25 changes: 21 additions & 4 deletions src/cli/operations/deploy/post-deploy-ab-tests.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -142,7 +142,7 @@ export async function setupABTests(options: SetupABTestsOptions): Promise<SetupA
const existingTest = existingABTests?.[testSpec.name];

// Resolve ARN references from deployed state
const resolvedVariants = resolveVariants(testSpec.variants, deployedResources);
const resolvedVariants = resolveVariants(testSpec.variants, projectSpec.name, deployedResources);
Comment thread
jariy17 marked this conversation as resolved.
const resolvedGatewayArn = resolveGatewayArn(testSpec.gatewayRef, deployedResources);
if (!resolvedGatewayArn.startsWith('arn:') || resolvedGatewayArn.split(':').length < 6) {
results.push({
Expand DownExpand Up@@ -409,7 +409,8 @@ async function findABTestByName(
/**
* Resolve variant config bundle references.
* If bundleArn is a name (not an ARN), look it up in deployed config bundles.
* Target-based variants are passed through as-is.
* Target-based variants have their target name prefixed with projectName to match
* what post-deploy-http-gateways.ts creates on AWS (e.g. `${projectName}-${tgt.name}`).
Comment thread
jariy17 marked this conversation as resolved.
*/
function resolveVariants(
variants: {
Expand All@@ -420,6 +421,7 @@ function resolveVariants(
target?: { targetName: string };
};
}[],
projectName: string,
deployedResources?: DeployedResourceState
): ABTestVariant[] {
return variants.map(v => {
Expand All@@ -436,12 +438,15 @@ function resolveVariants(
},
};
}
// Target-based variant — pass through
// Target-based variant — prepend projectName to match the AWS-side name created by
// post-deploy-http-gateways.ts: `${projectName}-${tgt.name}`
return {
name: v.name,
weight: v.weight,
variantConfiguration: {
...(v.variantConfiguration.target && { target: { name: v.variantConfiguration.target.targetName } }),
...(v.variantConfiguration.target && {
target: { name: resolveTargetName(v.variantConfiguration.target.targetName, projectName) },
}),
},
};
});
Expand DownExpand Up@@ -475,6 +480,18 @@ function resolveConfigBundleVersion(
return versionRef;
}

/**
* Resolve a variant target name, applying the project prefix if not already present.
* This handles legacy configs that were created before the prefix requirement.
*/
function resolveTargetName(targetName: string, projectName: string): string {
// If the target name already starts with the project prefix, use as-is to avoid double-prefixing
if (targetName.startsWith(`${projectName}-`)) {
return targetName;
}
return `${projectName}-${targetName}`;
}

function resolveGatewayArn(ref: string, deployedResources?: DeployedResourceState): string {
if (ref.startsWith('arn:')) return ref;

Expand Down
36 changes: 30 additions & 6 deletions src/cli/operations/deploy/post-deploy-http-gateways.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

for (const tgt of gwSpec.targets) {
const existingTarget = existingTargetsByName.get(tgt.name);
const existingTarget = existingTargetsByName.get(`${projectName}-${tgt.name}`);
if (existingTarget) {
// Target exists by name — check if qualifier matches
try {
Expand DownExpand Up@@ -143,7 +143,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: existingGateway.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand All@@ -170,7 +170,8 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

// Try to find by name via list (handles re-creation after state loss)
const existingByName = await findHttpGatewayByName(region, gwSpec.name);
const prefixedGatewayName = `${projectName}-${gwSpec.name}`;
const existingByName = await findHttpGatewayByName(region, prefixedGatewayName);
if (existingByName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" found by name but local state was lost. Target and role state may be incomplete — consider re-deploying.`
Expand All@@ -189,6 +190,29 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
continue;
}

// Migration fallback: try unprefixed name for pre-PR gateways (Comment 3 fix)
const existingByLegacyName = await findHttpGatewayByName(region, gwSpec.name);
if (existingByLegacyName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" was found using its pre-migration name. ` +
`This CLI version uses the naming convention "${prefixedGatewayName}". ` +
`The gateway has been recovered from state loss. ` +
`You may want to rename "${gwSpec.name}" to "${prefixedGatewayName}" on AWS to match the new convention.`
);
httpGateways[gwSpec.name] = {
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
// targetId, roleArn, roleCreatedByCli unknown after state-loss recovery
};
results.push({
gatewayName: gwSpec.name,
status: 'skipped',
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
});
continue;
}

// Resolve runtime ARN from deployed state
const runtimeState = deployedResources?.runtimes?.[gwSpec.runtimeRef];
if (!runtimeState) {
Expand DownExpand Up@@ -216,7 +240,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
// Creating HTTP gateway for runtime
const createResult = await createHttpGateway({
region,
name: gwSpec.name,
name: `${projectName}-${gwSpec.name}`,
roleArn: resolvedRoleArn,
});

Expand All@@ -231,7 +255,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const targetResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: gwSpec.runtimeRef,
targetName: `${projectName}-${gwSpec.runtimeRef}`,
runtimeArn,
});

Expand DownExpand Up@@ -288,7 +312,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand Down
34 changes: 34 additions & 0 deletions src/cli/operations/deploy/preflight.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ export function formatError(err: unknown): string {
* Returns the project context needed for subsequent steps.
*/
const MAX_RUNTIME_NAME_LENGTH = 48;
const MAX_GATEWAY_COMBINED_NAME_LENGTH = 48;

export async function validateProject(): Promise<PreflightContext> {
// Find the agentcore config directory, walking up from cwd if needed
Expand DownExpand Up@@ -108,6 +109,9 @@ export async function validateProject(): Promise<PreflightContext> {
// Validate runtime names don't exceed AWS limits
validateRuntimeNames(projectSpec);

// Validate HTTP gateway names don't exceed AWS limits when combined with project name
validateHttpGatewayNames(projectSpec);

// Validate Container agents have Dockerfiles
validateContainerAgents(projectSpec, configRoot);

Expand DownExpand Up@@ -140,6 +144,36 @@ function validateRuntimeNames(projectSpec: AgentCoreProjectSpec): void {
}
}

/**
* Validates that combined HTTP gateway names (projectName-gatewayName) don't exceed AWS limits.
*/
function validateHttpGatewayNames(projectSpec: AgentCoreProjectSpec): void {
const projectName = projectSpec.name;
for (const gateway of projectSpec.httpGateways ?? []) {
const gwName = gateway.name;
if (gwName) {
const combinedName = `${projectName}-${gwName}`;
if (combinedName.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
throw new Error(
`HTTP gateway name too long: "${combinedName}" (${combinedName.length} chars). ` +
`AWS limits gateway names to ${MAX_GATEWAY_COMBINED_NAME_LENGTH} characters. ` +
`Shorten the project name or gateway name in agentcore.json.`
);
}
}
for (const target of gateway.targets ?? []) {
const combined = `${projectName}-${target.name}`;
if (combined.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
const maxTargetLen = MAX_GATEWAY_COMBINED_NAME_LENGTH - projectName.length - 1;
throw new Error(
`HTTP gateway target "${target.name}" in gateway "${gwName}" would exceed the ${MAX_GATEWAY_COMBINED_NAME_LENGTH}-character AWS limit when prefixed with project name "${projectName}-" (total: ${combined.length} chars). ` +
`Shorten the target name to ${maxTargetLen} characters or fewer.`
);
}
}
}
}

/**
* Validates that Container agents have required Dockerfiles.
*/
Expand Down
12 changes: 6 additions & 6 deletions src/schema/schemas/primitives/__tests__/http-gateway.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,12 +22,12 @@ describe('HttpGatewayNameSchema', () => {
expect(HttpGatewayNameSchema.safeParse('my_gateway').success).toBe(false);
});

it('rejects name over 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(49)).success).toBe(false);
it('accepts name longer than 24 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(25)).success).toBe(true);
});

it('accepts name at 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(48)).success).toBe(true);
it('accepts name at 47 chars (room for 1-char project name + hyphen)', () => {
expect(HttpGatewayNameSchema.safeParse('a' + 'b'.repeat(46)).success).toBe(true);
});
});

Expand DownExpand Up@@ -60,8 +60,8 @@ describe('HttpGatewaySchema', () => {
expect(HttpGatewaySchema.safeParse(withoutRuntimeRef).success).toBe(false);
});

it('rejects name too long (>48 chars)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a'.repeat(49) }).success).toBe(false);
it('accepts name longer than 24 chars (no standalone max cap)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a' + 'b'.repeat(30) }).success).toBe(true);
});

it('rejects name starting with number', () => {
Expand Down
5 changes: 2 additions & 3 deletions src/schema/schemas/primitives/http-gateway.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,9 @@ import { z } from 'zod';
export const HttpGatewayNameSchema = z
.string()
.min(1, 'Name is required')
.max(48)
.regex(
/^[a-zA-Z][a-zA-Z0-9-]{0,47}$/,
'Must begin with a letter and contain only alphanumeric characters and hyphens (max 48 chars)'
Comment thread
jariy17 marked this conversation as resolved.
/^[a-zA-Z][a-zA-Z0-9-]*$/,
'Gateway name must start with a letter and contain only alphanumeric characters or hyphens (combined with project name must fit 48-char AWS limit)'
);

export const HttpGatewayTargetSchema = z.object({
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,13 +139,13 @@ describe('setupHttpGateways', () => {

expect(mockCreateHttpGateway).toHaveBeenCalledWith({
region: 'us-east-1',
name: 'MyHttpGw',
name: 'TestProject-MyHttpGw',
roleArn: 'arn:aws:iam::123456789012:role/ExistingRole',
});
expect(mockCreateHttpGatewayTarget).toHaveBeenCalledWith({
region: 'us-east-1',
gatewayId: 'gw-001',
targetName: 'my-agent',
targetName: 'TestProject-my-agent',
runtimeArn: 'arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/rt-123',
});
});
Expand DownExpand Up@@ -175,7 +175,7 @@ describe('setupHttpGateways', () => {

it('finds gateway by name via list (state loss recovery)', async () => {
mockListAllHttpGateways.mockResolvedValue([
{ name: 'MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
{ name: 'TestProject-MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
]);

const result = await setupHttpGateways({
Expand All@@ -190,6 +190,39 @@ describe('setupHttpGateways', () => {
expect(mockCreateHttpGateway).not.toHaveBeenCalled();
});

it('recovers state using legacy (pre-migration) gateway name when prefixed name not found', async () => {
// First call: prefixed name "TestProject-MyHttpGw" → not found
// Second call: unprefixed legacy name "MyHttpGw" → found
mockListAllHttpGateways
.mockResolvedValueOnce([])
.mockResolvedValueOnce([{ name: 'MyHttpGw', gatewayId: 'gw-legacy', gatewayArn: 'arn:httpgw:legacy' }]);

const warnSpy = vi.spyOn(console, 'warn').mockReturnValue(undefined);

const result = await setupHttpGateways({
region: 'us-east-1',
projectName: 'TestProject',
projectSpec: makeProjectSpec([sampleHttpGateway]),
deployedResources: sampleDeployedResources,
});

// findHttpGatewayByName was called twice: once for prefixed, once for unprefixed name
expect(mockListAllHttpGateways).toHaveBeenCalledTimes(2);

// Gateway result is skipped (not created)
expect(result.results[0]!.status).toBe('skipped');
expect(result.results[0]!.gatewayId).toBe('gw-legacy');
expect(result.httpGateways.MyHttpGw!.gatewayId).toBe('gw-legacy');

// createHttpGateway was NOT called
expect(mockCreateHttpGateway).not.toHaveBeenCalled();

// console.warn was called with the pre-migration warning text
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('pre-migration name'));

warnSpy.mockRestore();
});

it('reports error on missing runtime ref', async () => {
const emptyDeployedResources = {} as unknown as DeployedResourceState;

Expand Down
45 changes: 45 additions & 0 deletions src/cli/operations/deploy/__tests__/preflight.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -126,6 +126,51 @@ describe('validateProject', () => {
expect(result.projectSpec.name).toBe('test-project');
expect(result.isTeardownDeploy).toBe(false);
});

it('rejects gateway target name that exceeds 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (39) = 49 > 48
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(39), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

await expect(validateProject()).rejects.toThrow(
'HTTP gateway target "' + 'a'.repeat(39) + '" in gateway "gw" would exceed the 48-character AWS limit'
);
});

it('accepts gateway target name within 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (38) = 48 == limit
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(38), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

const result = await validateProject();
expect(result.projectSpec.name).toBe('myproject');
});
});

describe('formatError', () => {
Expand Down
25 changes: 21 additions & 4 deletions src/cli/operations/deploy/post-deploy-ab-tests.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -142,7 +142,7 @@ export async function setupABTests(options: SetupABTestsOptions): Promise<SetupA
const existingTest = existingABTests?.[testSpec.name];

// Resolve ARN references from deployed state
const resolvedVariants = resolveVariants(testSpec.variants, deployedResources);
const resolvedVariants = resolveVariants(testSpec.variants, projectSpec.name, deployedResources);
Comment thread
jariy17 marked this conversation as resolved.
const resolvedGatewayArn = resolveGatewayArn(testSpec.gatewayRef, deployedResources);
if (!resolvedGatewayArn.startsWith('arn:') || resolvedGatewayArn.split(':').length < 6) {
results.push({
Expand DownExpand Up@@ -409,7 +409,8 @@ async function findABTestByName(
/**
* Resolve variant config bundle references.
* If bundleArn is a name (not an ARN), look it up in deployed config bundles.
* Target-based variants are passed through as-is.
* Target-based variants have their target name prefixed with projectName to match
* what post-deploy-http-gateways.ts creates on AWS (e.g. `${projectName}-${tgt.name}`).
Comment thread
jariy17 marked this conversation as resolved.
*/
function resolveVariants(
variants: {
Expand All@@ -420,6 +421,7 @@ function resolveVariants(
target?: { targetName: string };
};
}[],
projectName: string,
deployedResources?: DeployedResourceState
): ABTestVariant[] {
return variants.map(v => {
Expand All@@ -436,12 +438,15 @@ function resolveVariants(
},
};
}
// Target-based variant — pass through
// Target-based variant — prepend projectName to match the AWS-side name created by
// post-deploy-http-gateways.ts: `${projectName}-${tgt.name}`
return {
name: v.name,
weight: v.weight,
variantConfiguration: {
...(v.variantConfiguration.target && { target: { name: v.variantConfiguration.target.targetName } }),
...(v.variantConfiguration.target && {
target: { name: resolveTargetName(v.variantConfiguration.target.targetName, projectName) },
}),
},
};
});
Expand DownExpand Up@@ -475,6 +480,18 @@ function resolveConfigBundleVersion(
return versionRef;
}

/**
* Resolve a variant target name, applying the project prefix if not already present.
* This handles legacy configs that were created before the prefix requirement.
*/
function resolveTargetName(targetName: string, projectName: string): string {
// If the target name already starts with the project prefix, use as-is to avoid double-prefixing
if (targetName.startsWith(`${projectName}-`)) {
return targetName;
}
return `${projectName}-${targetName}`;
}

function resolveGatewayArn(ref: string, deployedResources?: DeployedResourceState): string {
if (ref.startsWith('arn:')) return ref;

Expand Down
36 changes: 30 additions & 6 deletions src/cli/operations/deploy/post-deploy-http-gateways.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

for (const tgt of gwSpec.targets) {
const existingTarget = existingTargetsByName.get(tgt.name);
const existingTarget = existingTargetsByName.get(`${projectName}-${tgt.name}`);
if (existingTarget) {
// Target exists by name — check if qualifier matches
try {
Expand DownExpand Up@@ -143,7 +143,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: existingGateway.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand All@@ -170,7 +170,8 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

// Try to find by name via list (handles re-creation after state loss)
const existingByName = await findHttpGatewayByName(region, gwSpec.name);
const prefixedGatewayName = `${projectName}-${gwSpec.name}`;
const existingByName = await findHttpGatewayByName(region, prefixedGatewayName);
if (existingByName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" found by name but local state was lost. Target and role state may be incomplete — consider re-deploying.`
Expand All@@ -189,6 +190,29 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
continue;
}

// Migration fallback: try unprefixed name for pre-PR gateways (Comment 3 fix)
const existingByLegacyName = await findHttpGatewayByName(region, gwSpec.name);
if (existingByLegacyName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" was found using its pre-migration name. ` +
`This CLI version uses the naming convention "${prefixedGatewayName}". ` +
`The gateway has been recovered from state loss. ` +
`You may want to rename "${gwSpec.name}" to "${prefixedGatewayName}" on AWS to match the new convention.`
);
httpGateways[gwSpec.name] = {
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
// targetId, roleArn, roleCreatedByCli unknown after state-loss recovery
};
results.push({
gatewayName: gwSpec.name,
status: 'skipped',
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
});
continue;
}

// Resolve runtime ARN from deployed state
const runtimeState = deployedResources?.runtimes?.[gwSpec.runtimeRef];
if (!runtimeState) {
Expand DownExpand Up@@ -216,7 +240,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
// Creating HTTP gateway for runtime
const createResult = await createHttpGateway({
region,
name: gwSpec.name,
name: `${projectName}-${gwSpec.name}`,
roleArn: resolvedRoleArn,
});

Expand All@@ -231,7 +255,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const targetResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: gwSpec.runtimeRef,
targetName: `${projectName}-${gwSpec.runtimeRef}`,
runtimeArn,
});

Expand DownExpand Up@@ -288,7 +312,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand Down
34 changes: 34 additions & 0 deletions src/cli/operations/deploy/preflight.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ export function formatError(err: unknown): string {
* Returns the project context needed for subsequent steps.
*/
const MAX_RUNTIME_NAME_LENGTH = 48;
const MAX_GATEWAY_COMBINED_NAME_LENGTH = 48;

export async function validateProject(): Promise<PreflightContext> {
// Find the agentcore config directory, walking up from cwd if needed
Expand DownExpand Up@@ -108,6 +109,9 @@ export async function validateProject(): Promise<PreflightContext> {
// Validate runtime names don't exceed AWS limits
validateRuntimeNames(projectSpec);

// Validate HTTP gateway names don't exceed AWS limits when combined with project name
validateHttpGatewayNames(projectSpec);

// Validate Container agents have Dockerfiles
validateContainerAgents(projectSpec, configRoot);

Expand DownExpand Up@@ -140,6 +144,36 @@ function validateRuntimeNames(projectSpec: AgentCoreProjectSpec): void {
}
}

/**
* Validates that combined HTTP gateway names (projectName-gatewayName) don't exceed AWS limits.
*/
function validateHttpGatewayNames(projectSpec: AgentCoreProjectSpec): void {
const projectName = projectSpec.name;
for (const gateway of projectSpec.httpGateways ?? []) {
const gwName = gateway.name;
if (gwName) {
const combinedName = `${projectName}-${gwName}`;
if (combinedName.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
throw new Error(
`HTTP gateway name too long: "${combinedName}" (${combinedName.length} chars). ` +
`AWS limits gateway names to ${MAX_GATEWAY_COMBINED_NAME_LENGTH} characters. ` +
`Shorten the project name or gateway name in agentcore.json.`
);
}
}
for (const target of gateway.targets ?? []) {
const combined = `${projectName}-${target.name}`;
if (combined.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
const maxTargetLen = MAX_GATEWAY_COMBINED_NAME_LENGTH - projectName.length - 1;
throw new Error(
`HTTP gateway target "${target.name}" in gateway "${gwName}" would exceed the ${MAX_GATEWAY_COMBINED_NAME_LENGTH}-character AWS limit when prefixed with project name "${projectName}-" (total: ${combined.length} chars). ` +
`Shorten the target name to ${maxTargetLen} characters or fewer.`
);
}
}
}
}

/**
* Validates that Container agents have required Dockerfiles.
*/
Expand Down
12 changes: 6 additions & 6 deletions src/schema/schemas/primitives/__tests__/http-gateway.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,12 +22,12 @@ describe('HttpGatewayNameSchema', () => {
expect(HttpGatewayNameSchema.safeParse('my_gateway').success).toBe(false);
});

it('rejects name over 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(49)).success).toBe(false);
it('accepts name longer than 24 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(25)).success).toBe(true);
});

it('accepts name at 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(48)).success).toBe(true);
it('accepts name at 47 chars (room for 1-char project name + hyphen)', () => {
expect(HttpGatewayNameSchema.safeParse('a' + 'b'.repeat(46)).success).toBe(true);
});
});

Expand DownExpand Up@@ -60,8 +60,8 @@ describe('HttpGatewaySchema', () => {
expect(HttpGatewaySchema.safeParse(withoutRuntimeRef).success).toBe(false);
});

it('rejects name too long (>48 chars)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a'.repeat(49) }).success).toBe(false);
it('accepts name longer than 24 chars (no standalone max cap)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a' + 'b'.repeat(30) }).success).toBe(true);
});

it('rejects name starting with number', () => {
Expand Down
5 changes: 2 additions & 3 deletions src/schema/schemas/primitives/http-gateway.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,9 @@ import { z } from 'zod';
export const HttpGatewayNameSchema = z
.string()
.min(1, 'Name is required')
.max(48)
.regex(
/^[a-zA-Z][a-zA-Z0-9-]{0,47}$/,
'Must begin with a letter and contain only alphanumeric characters and hyphens (max 48 chars)'
Comment thread
jariy17 marked this conversation as resolved.
/^[a-zA-Z][a-zA-Z0-9-]*$/,
'Gateway name must start with a letter and contain only alphanumeric characters or hyphens (combined with project name must fit 48-char AWS limit)'
);

export const HttpGatewayTargetSchema = z.object({
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,13 +139,13 @@ describe('setupHttpGateways', () => {

expect(mockCreateHttpGateway).toHaveBeenCalledWith({
region: 'us-east-1',
name: 'MyHttpGw',
name: 'TestProject-MyHttpGw',
roleArn: 'arn:aws:iam::123456789012:role/ExistingRole',
});
expect(mockCreateHttpGatewayTarget).toHaveBeenCalledWith({
region: 'us-east-1',
gatewayId: 'gw-001',
targetName: 'my-agent',
targetName: 'TestProject-my-agent',
runtimeArn: 'arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/rt-123',
});
});
Expand DownExpand Up@@ -175,7 +175,7 @@ describe('setupHttpGateways', () => {

it('finds gateway by name via list (state loss recovery)', async () => {
mockListAllHttpGateways.mockResolvedValue([
{ name: 'MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
{ name: 'TestProject-MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
]);

const result = await setupHttpGateways({
Expand All@@ -190,6 +190,39 @@ describe('setupHttpGateways', () => {
expect(mockCreateHttpGateway).not.toHaveBeenCalled();
});

it('recovers state using legacy (pre-migration) gateway name when prefixed name not found', async () => {
// First call: prefixed name "TestProject-MyHttpGw" → not found
// Second call: unprefixed legacy name "MyHttpGw" → found
mockListAllHttpGateways
.mockResolvedValueOnce([])
.mockResolvedValueOnce([{ name: 'MyHttpGw', gatewayId: 'gw-legacy', gatewayArn: 'arn:httpgw:legacy' }]);

const warnSpy = vi.spyOn(console, 'warn').mockReturnValue(undefined);

const result = await setupHttpGateways({
region: 'us-east-1',
projectName: 'TestProject',
projectSpec: makeProjectSpec([sampleHttpGateway]),
deployedResources: sampleDeployedResources,
});

// findHttpGatewayByName was called twice: once for prefixed, once for unprefixed name
expect(mockListAllHttpGateways).toHaveBeenCalledTimes(2);

// Gateway result is skipped (not created)
expect(result.results[0]!.status).toBe('skipped');
expect(result.results[0]!.gatewayId).toBe('gw-legacy');
expect(result.httpGateways.MyHttpGw!.gatewayId).toBe('gw-legacy');

// createHttpGateway was NOT called
expect(mockCreateHttpGateway).not.toHaveBeenCalled();

// console.warn was called with the pre-migration warning text
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('pre-migration name'));

warnSpy.mockRestore();
});

it('reports error on missing runtime ref', async () => {
const emptyDeployedResources = {} as unknown as DeployedResourceState;

Expand Down
45 changes: 45 additions & 0 deletions src/cli/operations/deploy/__tests__/preflight.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -126,6 +126,51 @@ describe('validateProject', () => {
expect(result.projectSpec.name).toBe('test-project');
expect(result.isTeardownDeploy).toBe(false);
});

it('rejects gateway target name that exceeds 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (39) = 49 > 48
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(39), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

await expect(validateProject()).rejects.toThrow(
'HTTP gateway target "' + 'a'.repeat(39) + '" in gateway "gw" would exceed the 48-character AWS limit'
);
});

it('accepts gateway target name within 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (38) = 48 == limit
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(38), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

const result = await validateProject();
expect(result.projectSpec.name).toBe('myproject');
});
});

describe('formatError', () => {
Expand Down
25 changes: 21 additions & 4 deletions src/cli/operations/deploy/post-deploy-ab-tests.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -142,7 +142,7 @@ export async function setupABTests(options: SetupABTestsOptions): Promise<SetupA
const existingTest = existingABTests?.[testSpec.name];

// Resolve ARN references from deployed state
const resolvedVariants = resolveVariants(testSpec.variants, deployedResources);
const resolvedVariants = resolveVariants(testSpec.variants, projectSpec.name, deployedResources);
Comment thread
jariy17 marked this conversation as resolved.
const resolvedGatewayArn = resolveGatewayArn(testSpec.gatewayRef, deployedResources);
if (!resolvedGatewayArn.startsWith('arn:') || resolvedGatewayArn.split(':').length < 6) {
results.push({
Expand DownExpand Up@@ -409,7 +409,8 @@ async function findABTestByName(
/**
* Resolve variant config bundle references.
* If bundleArn is a name (not an ARN), look it up in deployed config bundles.
* Target-based variants are passed through as-is.
* Target-based variants have their target name prefixed with projectName to match
* what post-deploy-http-gateways.ts creates on AWS (e.g. `${projectName}-${tgt.name}`).
Comment thread
jariy17 marked this conversation as resolved.
*/
function resolveVariants(
variants: {
Expand All@@ -420,6 +421,7 @@ function resolveVariants(
target?: { targetName: string };
};
}[],
projectName: string,
deployedResources?: DeployedResourceState
): ABTestVariant[] {
return variants.map(v => {
Expand All@@ -436,12 +438,15 @@ function resolveVariants(
},
};
}
// Target-based variant — pass through
// Target-based variant — prepend projectName to match the AWS-side name created by
// post-deploy-http-gateways.ts: `${projectName}-${tgt.name}`
return {
name: v.name,
weight: v.weight,
variantConfiguration: {
...(v.variantConfiguration.target && { target: { name: v.variantConfiguration.target.targetName } }),
...(v.variantConfiguration.target && {
target: { name: resolveTargetName(v.variantConfiguration.target.targetName, projectName) },
}),
},
};
});
Expand DownExpand Up@@ -475,6 +480,18 @@ function resolveConfigBundleVersion(
return versionRef;
}

/**
* Resolve a variant target name, applying the project prefix if not already present.
* This handles legacy configs that were created before the prefix requirement.
*/
function resolveTargetName(targetName: string, projectName: string): string {
// If the target name already starts with the project prefix, use as-is to avoid double-prefixing
if (targetName.startsWith(`${projectName}-`)) {
return targetName;
}
return `${projectName}-${targetName}`;
}

function resolveGatewayArn(ref: string, deployedResources?: DeployedResourceState): string {
if (ref.startsWith('arn:')) return ref;

Expand Down
36 changes: 30 additions & 6 deletions src/cli/operations/deploy/post-deploy-http-gateways.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

for (const tgt of gwSpec.targets) {
const existingTarget = existingTargetsByName.get(tgt.name);
const existingTarget = existingTargetsByName.get(`${projectName}-${tgt.name}`);
if (existingTarget) {
// Target exists by name — check if qualifier matches
try {
Expand DownExpand Up@@ -143,7 +143,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: existingGateway.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand All@@ -170,7 +170,8 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

// Try to find by name via list (handles re-creation after state loss)
const existingByName = await findHttpGatewayByName(region, gwSpec.name);
const prefixedGatewayName = `${projectName}-${gwSpec.name}`;
const existingByName = await findHttpGatewayByName(region, prefixedGatewayName);
if (existingByName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" found by name but local state was lost. Target and role state may be incomplete — consider re-deploying.`
Expand All@@ -189,6 +190,29 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
continue;
}

// Migration fallback: try unprefixed name for pre-PR gateways (Comment 3 fix)
const existingByLegacyName = await findHttpGatewayByName(region, gwSpec.name);
if (existingByLegacyName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" was found using its pre-migration name. ` +
`This CLI version uses the naming convention "${prefixedGatewayName}". ` +
`The gateway has been recovered from state loss. ` +
`You may want to rename "${gwSpec.name}" to "${prefixedGatewayName}" on AWS to match the new convention.`
);
httpGateways[gwSpec.name] = {
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
// targetId, roleArn, roleCreatedByCli unknown after state-loss recovery
};
results.push({
gatewayName: gwSpec.name,
status: 'skipped',
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
});
continue;
}

// Resolve runtime ARN from deployed state
const runtimeState = deployedResources?.runtimes?.[gwSpec.runtimeRef];
if (!runtimeState) {
Expand DownExpand Up@@ -216,7 +240,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
// Creating HTTP gateway for runtime
const createResult = await createHttpGateway({
region,
name: gwSpec.name,
name: `${projectName}-${gwSpec.name}`,
roleArn: resolvedRoleArn,
});

Expand All@@ -231,7 +255,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const targetResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: gwSpec.runtimeRef,
targetName: `${projectName}-${gwSpec.runtimeRef}`,
runtimeArn,
});

Expand DownExpand Up@@ -288,7 +312,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand Down
34 changes: 34 additions & 0 deletions src/cli/operations/deploy/preflight.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ export function formatError(err: unknown): string {
* Returns the project context needed for subsequent steps.
*/
const MAX_RUNTIME_NAME_LENGTH = 48;
const MAX_GATEWAY_COMBINED_NAME_LENGTH = 48;

export async function validateProject(): Promise<PreflightContext> {
// Find the agentcore config directory, walking up from cwd if needed
Expand DownExpand Up@@ -108,6 +109,9 @@ export async function validateProject(): Promise<PreflightContext> {
// Validate runtime names don't exceed AWS limits
validateRuntimeNames(projectSpec);

// Validate HTTP gateway names don't exceed AWS limits when combined with project name
validateHttpGatewayNames(projectSpec);

// Validate Container agents have Dockerfiles
validateContainerAgents(projectSpec, configRoot);

Expand DownExpand Up@@ -140,6 +144,36 @@ function validateRuntimeNames(projectSpec: AgentCoreProjectSpec): void {
}
}

/**
* Validates that combined HTTP gateway names (projectName-gatewayName) don't exceed AWS limits.
*/
function validateHttpGatewayNames(projectSpec: AgentCoreProjectSpec): void {
const projectName = projectSpec.name;
for (const gateway of projectSpec.httpGateways ?? []) {
const gwName = gateway.name;
if (gwName) {
const combinedName = `${projectName}-${gwName}`;
if (combinedName.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
throw new Error(
`HTTP gateway name too long: "${combinedName}" (${combinedName.length} chars). ` +
`AWS limits gateway names to ${MAX_GATEWAY_COMBINED_NAME_LENGTH} characters. ` +
`Shorten the project name or gateway name in agentcore.json.`
);
}
}
for (const target of gateway.targets ?? []) {
const combined = `${projectName}-${target.name}`;
if (combined.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
const maxTargetLen = MAX_GATEWAY_COMBINED_NAME_LENGTH - projectName.length - 1;
throw new Error(
`HTTP gateway target "${target.name}" in gateway "${gwName}" would exceed the ${MAX_GATEWAY_COMBINED_NAME_LENGTH}-character AWS limit when prefixed with project name "${projectName}-" (total: ${combined.length} chars). ` +
`Shorten the target name to ${maxTargetLen} characters or fewer.`
);
}
}
}
}

/**
* Validates that Container agents have required Dockerfiles.
*/
Expand Down
12 changes: 6 additions & 6 deletions src/schema/schemas/primitives/__tests__/http-gateway.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,12 +22,12 @@ describe('HttpGatewayNameSchema', () => {
expect(HttpGatewayNameSchema.safeParse('my_gateway').success).toBe(false);
});

it('rejects name over 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(49)).success).toBe(false);
it('accepts name longer than 24 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(25)).success).toBe(true);
});

it('accepts name at 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(48)).success).toBe(true);
it('accepts name at 47 chars (room for 1-char project name + hyphen)', () => {
expect(HttpGatewayNameSchema.safeParse('a' + 'b'.repeat(46)).success).toBe(true);
});
});

Expand DownExpand Up@@ -60,8 +60,8 @@ describe('HttpGatewaySchema', () => {
expect(HttpGatewaySchema.safeParse(withoutRuntimeRef).success).toBe(false);
});

it('rejects name too long (>48 chars)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a'.repeat(49) }).success).toBe(false);
it('accepts name longer than 24 chars (no standalone max cap)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a' + 'b'.repeat(30) }).success).toBe(true);
});

it('rejects name starting with number', () => {
Expand Down
5 changes: 2 additions & 3 deletions src/schema/schemas/primitives/http-gateway.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,9 @@ import { z } from 'zod';
export const HttpGatewayNameSchema = z
.string()
.min(1, 'Name is required')
.max(48)
.regex(
/^[a-zA-Z][a-zA-Z0-9-]{0,47}$/,
'Must begin with a letter and contain only alphanumeric characters and hyphens (max 48 chars)'
Comment thread
jariy17 marked this conversation as resolved.
/^[a-zA-Z][a-zA-Z0-9-]*$/,
'Gateway name must start with a letter and contain only alphanumeric characters or hyphens (combined with project name must fit 48-char AWS limit)'
);

export const HttpGatewayTargetSchema = z.object({
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,13 +139,13 @@ describe('setupHttpGateways', () => {

expect(mockCreateHttpGateway).toHaveBeenCalledWith({
region: 'us-east-1',
name: 'MyHttpGw',
name: 'TestProject-MyHttpGw',
roleArn: 'arn:aws:iam::123456789012:role/ExistingRole',
});
expect(mockCreateHttpGatewayTarget).toHaveBeenCalledWith({
region: 'us-east-1',
gatewayId: 'gw-001',
targetName: 'my-agent',
targetName: 'TestProject-my-agent',
runtimeArn: 'arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/rt-123',
});
});
Expand DownExpand Up@@ -175,7 +175,7 @@ describe('setupHttpGateways', () => {

it('finds gateway by name via list (state loss recovery)', async () => {
mockListAllHttpGateways.mockResolvedValue([
{ name: 'MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
{ name: 'TestProject-MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
]);

const result = await setupHttpGateways({
Expand All@@ -190,6 +190,39 @@ describe('setupHttpGateways', () => {
expect(mockCreateHttpGateway).not.toHaveBeenCalled();
});

it('recovers state using legacy (pre-migration) gateway name when prefixed name not found', async () => {
// First call: prefixed name "TestProject-MyHttpGw" → not found
// Second call: unprefixed legacy name "MyHttpGw" → found
mockListAllHttpGateways
.mockResolvedValueOnce([])
.mockResolvedValueOnce([{ name: 'MyHttpGw', gatewayId: 'gw-legacy', gatewayArn: 'arn:httpgw:legacy' }]);

const warnSpy = vi.spyOn(console, 'warn').mockReturnValue(undefined);

const result = await setupHttpGateways({
region: 'us-east-1',
projectName: 'TestProject',
projectSpec: makeProjectSpec([sampleHttpGateway]),
deployedResources: sampleDeployedResources,
});

// findHttpGatewayByName was called twice: once for prefixed, once for unprefixed name
expect(mockListAllHttpGateways).toHaveBeenCalledTimes(2);

// Gateway result is skipped (not created)
expect(result.results[0]!.status).toBe('skipped');
expect(result.results[0]!.gatewayId).toBe('gw-legacy');
expect(result.httpGateways.MyHttpGw!.gatewayId).toBe('gw-legacy');

// createHttpGateway was NOT called
expect(mockCreateHttpGateway).not.toHaveBeenCalled();

// console.warn was called with the pre-migration warning text
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('pre-migration name'));

warnSpy.mockRestore();
});

it('reports error on missing runtime ref', async () => {
const emptyDeployedResources = {} as unknown as DeployedResourceState;

Expand Down
45 changes: 45 additions & 0 deletions src/cli/operations/deploy/__tests__/preflight.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -126,6 +126,51 @@ describe('validateProject', () => {
expect(result.projectSpec.name).toBe('test-project');
expect(result.isTeardownDeploy).toBe(false);
});

it('rejects gateway target name that exceeds 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (39) = 49 > 48
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(39), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

await expect(validateProject()).rejects.toThrow(
'HTTP gateway target "' + 'a'.repeat(39) + '" in gateway "gw" would exceed the 48-character AWS limit'
);
});

it('accepts gateway target name within 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (38) = 48 == limit
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(38), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

const result = await validateProject();
expect(result.projectSpec.name).toBe('myproject');
});
});

describe('formatError', () => {
Expand Down
25 changes: 21 additions & 4 deletions src/cli/operations/deploy/post-deploy-ab-tests.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -142,7 +142,7 @@ export async function setupABTests(options: SetupABTestsOptions): Promise<SetupA
const existingTest = existingABTests?.[testSpec.name];

// Resolve ARN references from deployed state
const resolvedVariants = resolveVariants(testSpec.variants, deployedResources);
const resolvedVariants = resolveVariants(testSpec.variants, projectSpec.name, deployedResources);
Comment thread
jariy17 marked this conversation as resolved.
const resolvedGatewayArn = resolveGatewayArn(testSpec.gatewayRef, deployedResources);
if (!resolvedGatewayArn.startsWith('arn:') || resolvedGatewayArn.split(':').length < 6) {
results.push({
Expand DownExpand Up@@ -409,7 +409,8 @@ async function findABTestByName(
/**
* Resolve variant config bundle references.
* If bundleArn is a name (not an ARN), look it up in deployed config bundles.
* Target-based variants are passed through as-is.
* Target-based variants have their target name prefixed with projectName to match
* what post-deploy-http-gateways.ts creates on AWS (e.g. `${projectName}-${tgt.name}`).
Comment thread
jariy17 marked this conversation as resolved.
*/
function resolveVariants(
variants: {
Expand All@@ -420,6 +421,7 @@ function resolveVariants(
target?: { targetName: string };
};
}[],
projectName: string,
deployedResources?: DeployedResourceState
): ABTestVariant[] {
return variants.map(v => {
Expand All@@ -436,12 +438,15 @@ function resolveVariants(
},
};
}
// Target-based variant — pass through
// Target-based variant — prepend projectName to match the AWS-side name created by
// post-deploy-http-gateways.ts: `${projectName}-${tgt.name}`
return {
name: v.name,
weight: v.weight,
variantConfiguration: {
...(v.variantConfiguration.target && { target: { name: v.variantConfiguration.target.targetName } }),
...(v.variantConfiguration.target && {
target: { name: resolveTargetName(v.variantConfiguration.target.targetName, projectName) },
}),
},
};
});
Expand DownExpand Up@@ -475,6 +480,18 @@ function resolveConfigBundleVersion(
return versionRef;
}

/**
* Resolve a variant target name, applying the project prefix if not already present.
* This handles legacy configs that were created before the prefix requirement.
*/
function resolveTargetName(targetName: string, projectName: string): string {
// If the target name already starts with the project prefix, use as-is to avoid double-prefixing
if (targetName.startsWith(`${projectName}-`)) {
return targetName;
}
return `${projectName}-${targetName}`;
}

function resolveGatewayArn(ref: string, deployedResources?: DeployedResourceState): string {
if (ref.startsWith('arn:')) return ref;

Expand Down
36 changes: 30 additions & 6 deletions src/cli/operations/deploy/post-deploy-http-gateways.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

for (const tgt of gwSpec.targets) {
const existingTarget = existingTargetsByName.get(tgt.name);
const existingTarget = existingTargetsByName.get(`${projectName}-${tgt.name}`);
if (existingTarget) {
// Target exists by name — check if qualifier matches
try {
Expand DownExpand Up@@ -143,7 +143,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: existingGateway.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand All@@ -170,7 +170,8 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

// Try to find by name via list (handles re-creation after state loss)
const existingByName = await findHttpGatewayByName(region, gwSpec.name);
const prefixedGatewayName = `${projectName}-${gwSpec.name}`;
const existingByName = await findHttpGatewayByName(region, prefixedGatewayName);
if (existingByName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" found by name but local state was lost. Target and role state may be incomplete — consider re-deploying.`
Expand All@@ -189,6 +190,29 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
continue;
}

// Migration fallback: try unprefixed name for pre-PR gateways (Comment 3 fix)
const existingByLegacyName = await findHttpGatewayByName(region, gwSpec.name);
if (existingByLegacyName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" was found using its pre-migration name. ` +
`This CLI version uses the naming convention "${prefixedGatewayName}". ` +
`The gateway has been recovered from state loss. ` +
`You may want to rename "${gwSpec.name}" to "${prefixedGatewayName}" on AWS to match the new convention.`
);
httpGateways[gwSpec.name] = {
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
// targetId, roleArn, roleCreatedByCli unknown after state-loss recovery
};
results.push({
gatewayName: gwSpec.name,
status: 'skipped',
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
});
continue;
}

// Resolve runtime ARN from deployed state
const runtimeState = deployedResources?.runtimes?.[gwSpec.runtimeRef];
if (!runtimeState) {
Expand DownExpand Up@@ -216,7 +240,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
// Creating HTTP gateway for runtime
const createResult = await createHttpGateway({
region,
name: gwSpec.name,
name: `${projectName}-${gwSpec.name}`,
roleArn: resolvedRoleArn,
});

Expand All@@ -231,7 +255,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const targetResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: gwSpec.runtimeRef,
targetName: `${projectName}-${gwSpec.runtimeRef}`,
runtimeArn,
});

Expand DownExpand Up@@ -288,7 +312,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand Down
34 changes: 34 additions & 0 deletions src/cli/operations/deploy/preflight.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ export function formatError(err: unknown): string {
* Returns the project context needed for subsequent steps.
*/
const MAX_RUNTIME_NAME_LENGTH = 48;
const MAX_GATEWAY_COMBINED_NAME_LENGTH = 48;

export async function validateProject(): Promise<PreflightContext> {
// Find the agentcore config directory, walking up from cwd if needed
Expand DownExpand Up@@ -108,6 +109,9 @@ export async function validateProject(): Promise<PreflightContext> {
// Validate runtime names don't exceed AWS limits
validateRuntimeNames(projectSpec);

// Validate HTTP gateway names don't exceed AWS limits when combined with project name
validateHttpGatewayNames(projectSpec);

// Validate Container agents have Dockerfiles
validateContainerAgents(projectSpec, configRoot);

Expand DownExpand Up@@ -140,6 +144,36 @@ function validateRuntimeNames(projectSpec: AgentCoreProjectSpec): void {
}
}

/**
* Validates that combined HTTP gateway names (projectName-gatewayName) don't exceed AWS limits.
*/
function validateHttpGatewayNames(projectSpec: AgentCoreProjectSpec): void {
const projectName = projectSpec.name;
for (const gateway of projectSpec.httpGateways ?? []) {
const gwName = gateway.name;
if (gwName) {
const combinedName = `${projectName}-${gwName}`;
if (combinedName.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
throw new Error(
`HTTP gateway name too long: "${combinedName}" (${combinedName.length} chars). ` +
`AWS limits gateway names to ${MAX_GATEWAY_COMBINED_NAME_LENGTH} characters. ` +
`Shorten the project name or gateway name in agentcore.json.`
);
}
}
for (const target of gateway.targets ?? []) {
const combined = `${projectName}-${target.name}`;
if (combined.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
const maxTargetLen = MAX_GATEWAY_COMBINED_NAME_LENGTH - projectName.length - 1;
throw new Error(
`HTTP gateway target "${target.name}" in gateway "${gwName}" would exceed the ${MAX_GATEWAY_COMBINED_NAME_LENGTH}-character AWS limit when prefixed with project name "${projectName}-" (total: ${combined.length} chars). ` +
`Shorten the target name to ${maxTargetLen} characters or fewer.`
);
}
}
}
}

/**
* Validates that Container agents have required Dockerfiles.
*/
Expand Down
12 changes: 6 additions & 6 deletions src/schema/schemas/primitives/__tests__/http-gateway.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,12 +22,12 @@ describe('HttpGatewayNameSchema', () => {
expect(HttpGatewayNameSchema.safeParse('my_gateway').success).toBe(false);
});

it('rejects name over 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(49)).success).toBe(false);
it('accepts name longer than 24 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(25)).success).toBe(true);
});

it('accepts name at 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(48)).success).toBe(true);
it('accepts name at 47 chars (room for 1-char project name + hyphen)', () => {
expect(HttpGatewayNameSchema.safeParse('a' + 'b'.repeat(46)).success).toBe(true);
});
});

Expand DownExpand Up@@ -60,8 +60,8 @@ describe('HttpGatewaySchema', () => {
expect(HttpGatewaySchema.safeParse(withoutRuntimeRef).success).toBe(false);
});

it('rejects name too long (>48 chars)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a'.repeat(49) }).success).toBe(false);
it('accepts name longer than 24 chars (no standalone max cap)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a' + 'b'.repeat(30) }).success).toBe(true);
});

it('rejects name starting with number', () => {
Expand Down
5 changes: 2 additions & 3 deletions src/schema/schemas/primitives/http-gateway.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,9 @@ import { z } from 'zod';
export const HttpGatewayNameSchema = z
.string()
.min(1, 'Name is required')
.max(48)
.regex(
/^[a-zA-Z][a-zA-Z0-9-]{0,47}$/,
'Must begin with a letter and contain only alphanumeric characters and hyphens (max 48 chars)'
Comment thread
jariy17 marked this conversation as resolved.
/^[a-zA-Z][a-zA-Z0-9-]*$/,
'Gateway name must start with a letter and contain only alphanumeric characters or hyphens (combined with project name must fit 48-char AWS limit)'
);

export const HttpGatewayTargetSchema = z.object({
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,13 +139,13 @@ describe('setupHttpGateways', () => {

expect(mockCreateHttpGateway).toHaveBeenCalledWith({
region: 'us-east-1',
name: 'MyHttpGw',
name: 'TestProject-MyHttpGw',
roleArn: 'arn:aws:iam::123456789012:role/ExistingRole',
});
expect(mockCreateHttpGatewayTarget).toHaveBeenCalledWith({
region: 'us-east-1',
gatewayId: 'gw-001',
targetName: 'my-agent',
targetName: 'TestProject-my-agent',
runtimeArn: 'arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/rt-123',
});
});
Expand DownExpand Up@@ -175,7 +175,7 @@ describe('setupHttpGateways', () => {

it('finds gateway by name via list (state loss recovery)', async () => {
mockListAllHttpGateways.mockResolvedValue([
{ name: 'MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
{ name: 'TestProject-MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
]);

const result = await setupHttpGateways({
Expand All@@ -190,6 +190,39 @@ describe('setupHttpGateways', () => {
expect(mockCreateHttpGateway).not.toHaveBeenCalled();
});

it('recovers state using legacy (pre-migration) gateway name when prefixed name not found', async () => {
// First call: prefixed name "TestProject-MyHttpGw" → not found
// Second call: unprefixed legacy name "MyHttpGw" → found
mockListAllHttpGateways
.mockResolvedValueOnce([])
.mockResolvedValueOnce([{ name: 'MyHttpGw', gatewayId: 'gw-legacy', gatewayArn: 'arn:httpgw:legacy' }]);

const warnSpy = vi.spyOn(console, 'warn').mockReturnValue(undefined);

const result = await setupHttpGateways({
region: 'us-east-1',
projectName: 'TestProject',
projectSpec: makeProjectSpec([sampleHttpGateway]),
deployedResources: sampleDeployedResources,
});

// findHttpGatewayByName was called twice: once for prefixed, once for unprefixed name
expect(mockListAllHttpGateways).toHaveBeenCalledTimes(2);

// Gateway result is skipped (not created)
expect(result.results[0]!.status).toBe('skipped');
expect(result.results[0]!.gatewayId).toBe('gw-legacy');
expect(result.httpGateways.MyHttpGw!.gatewayId).toBe('gw-legacy');

// createHttpGateway was NOT called
expect(mockCreateHttpGateway).not.toHaveBeenCalled();

// console.warn was called with the pre-migration warning text
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('pre-migration name'));

warnSpy.mockRestore();
});

it('reports error on missing runtime ref', async () => {
const emptyDeployedResources = {} as unknown as DeployedResourceState;

Expand Down
45 changes: 45 additions & 0 deletions src/cli/operations/deploy/__tests__/preflight.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -126,6 +126,51 @@ describe('validateProject', () => {
expect(result.projectSpec.name).toBe('test-project');
expect(result.isTeardownDeploy).toBe(false);
});

it('rejects gateway target name that exceeds 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (39) = 49 > 48
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(39), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

await expect(validateProject()).rejects.toThrow(
'HTTP gateway target "' + 'a'.repeat(39) + '" in gateway "gw" would exceed the 48-character AWS limit'
);
});

it('accepts gateway target name within 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (38) = 48 == limit
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(38), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

const result = await validateProject();
expect(result.projectSpec.name).toBe('myproject');
});
});

describe('formatError', () => {
Expand Down
25 changes: 21 additions & 4 deletions src/cli/operations/deploy/post-deploy-ab-tests.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -142,7 +142,7 @@ export async function setupABTests(options: SetupABTestsOptions): Promise<SetupA
const existingTest = existingABTests?.[testSpec.name];

// Resolve ARN references from deployed state
const resolvedVariants = resolveVariants(testSpec.variants, deployedResources);
const resolvedVariants = resolveVariants(testSpec.variants, projectSpec.name, deployedResources);
Comment thread
jariy17 marked this conversation as resolved.
const resolvedGatewayArn = resolveGatewayArn(testSpec.gatewayRef, deployedResources);
if (!resolvedGatewayArn.startsWith('arn:') || resolvedGatewayArn.split(':').length < 6) {
results.push({
Expand DownExpand Up@@ -409,7 +409,8 @@ async function findABTestByName(
/**
* Resolve variant config bundle references.
* If bundleArn is a name (not an ARN), look it up in deployed config bundles.
* Target-based variants are passed through as-is.
* Target-based variants have their target name prefixed with projectName to match
* what post-deploy-http-gateways.ts creates on AWS (e.g. `${projectName}-${tgt.name}`).
Comment thread
jariy17 marked this conversation as resolved.
*/
function resolveVariants(
variants: {
Expand All@@ -420,6 +421,7 @@ function resolveVariants(
target?: { targetName: string };
};
}[],
projectName: string,
deployedResources?: DeployedResourceState
): ABTestVariant[] {
return variants.map(v => {
Expand All@@ -436,12 +438,15 @@ function resolveVariants(
},
};
}
// Target-based variant — pass through
// Target-based variant — prepend projectName to match the AWS-side name created by
// post-deploy-http-gateways.ts: `${projectName}-${tgt.name}`
return {
name: v.name,
weight: v.weight,
variantConfiguration: {
...(v.variantConfiguration.target && { target: { name: v.variantConfiguration.target.targetName } }),
...(v.variantConfiguration.target && {
target: { name: resolveTargetName(v.variantConfiguration.target.targetName, projectName) },
}),
},
};
});
Expand DownExpand Up@@ -475,6 +480,18 @@ function resolveConfigBundleVersion(
return versionRef;
}

/**
* Resolve a variant target name, applying the project prefix if not already present.
* This handles legacy configs that were created before the prefix requirement.
*/
function resolveTargetName(targetName: string, projectName: string): string {
// If the target name already starts with the project prefix, use as-is to avoid double-prefixing
if (targetName.startsWith(`${projectName}-`)) {
return targetName;
}
return `${projectName}-${targetName}`;
}

function resolveGatewayArn(ref: string, deployedResources?: DeployedResourceState): string {
if (ref.startsWith('arn:')) return ref;

Expand Down
36 changes: 30 additions & 6 deletions src/cli/operations/deploy/post-deploy-http-gateways.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

for (const tgt of gwSpec.targets) {
const existingTarget = existingTargetsByName.get(tgt.name);
const existingTarget = existingTargetsByName.get(`${projectName}-${tgt.name}`);
if (existingTarget) {
// Target exists by name — check if qualifier matches
try {
Expand DownExpand Up@@ -143,7 +143,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: existingGateway.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand All@@ -170,7 +170,8 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

// Try to find by name via list (handles re-creation after state loss)
const existingByName = await findHttpGatewayByName(region, gwSpec.name);
const prefixedGatewayName = `${projectName}-${gwSpec.name}`;
const existingByName = await findHttpGatewayByName(region, prefixedGatewayName);
if (existingByName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" found by name but local state was lost. Target and role state may be incomplete — consider re-deploying.`
Expand All@@ -189,6 +190,29 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
continue;
}

// Migration fallback: try unprefixed name for pre-PR gateways (Comment 3 fix)
const existingByLegacyName = await findHttpGatewayByName(region, gwSpec.name);
if (existingByLegacyName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" was found using its pre-migration name. ` +
`This CLI version uses the naming convention "${prefixedGatewayName}". ` +
`The gateway has been recovered from state loss. ` +
`You may want to rename "${gwSpec.name}" to "${prefixedGatewayName}" on AWS to match the new convention.`
);
httpGateways[gwSpec.name] = {
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
// targetId, roleArn, roleCreatedByCli unknown after state-loss recovery
};
results.push({
gatewayName: gwSpec.name,
status: 'skipped',
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
});
continue;
}

// Resolve runtime ARN from deployed state
const runtimeState = deployedResources?.runtimes?.[gwSpec.runtimeRef];
if (!runtimeState) {
Expand DownExpand Up@@ -216,7 +240,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
// Creating HTTP gateway for runtime
const createResult = await createHttpGateway({
region,
name: gwSpec.name,
name: `${projectName}-${gwSpec.name}`,
roleArn: resolvedRoleArn,
});

Expand All@@ -231,7 +255,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const targetResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: gwSpec.runtimeRef,
targetName: `${projectName}-${gwSpec.runtimeRef}`,
runtimeArn,
});

Expand DownExpand Up@@ -288,7 +312,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand Down
34 changes: 34 additions & 0 deletions src/cli/operations/deploy/preflight.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ export function formatError(err: unknown): string {
* Returns the project context needed for subsequent steps.
*/
const MAX_RUNTIME_NAME_LENGTH = 48;
const MAX_GATEWAY_COMBINED_NAME_LENGTH = 48;

export async function validateProject(): Promise<PreflightContext> {
// Find the agentcore config directory, walking up from cwd if needed
Expand DownExpand Up@@ -108,6 +109,9 @@ export async function validateProject(): Promise<PreflightContext> {
// Validate runtime names don't exceed AWS limits
validateRuntimeNames(projectSpec);

// Validate HTTP gateway names don't exceed AWS limits when combined with project name
validateHttpGatewayNames(projectSpec);

// Validate Container agents have Dockerfiles
validateContainerAgents(projectSpec, configRoot);

Expand DownExpand Up@@ -140,6 +144,36 @@ function validateRuntimeNames(projectSpec: AgentCoreProjectSpec): void {
}
}

/**
* Validates that combined HTTP gateway names (projectName-gatewayName) don't exceed AWS limits.
*/
function validateHttpGatewayNames(projectSpec: AgentCoreProjectSpec): void {
const projectName = projectSpec.name;
for (const gateway of projectSpec.httpGateways ?? []) {
const gwName = gateway.name;
if (gwName) {
const combinedName = `${projectName}-${gwName}`;
if (combinedName.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
throw new Error(
`HTTP gateway name too long: "${combinedName}" (${combinedName.length} chars). ` +
`AWS limits gateway names to ${MAX_GATEWAY_COMBINED_NAME_LENGTH} characters. ` +
`Shorten the project name or gateway name in agentcore.json.`
);
}
}
for (const target of gateway.targets ?? []) {
const combined = `${projectName}-${target.name}`;
if (combined.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
const maxTargetLen = MAX_GATEWAY_COMBINED_NAME_LENGTH - projectName.length - 1;
throw new Error(
`HTTP gateway target "${target.name}" in gateway "${gwName}" would exceed the ${MAX_GATEWAY_COMBINED_NAME_LENGTH}-character AWS limit when prefixed with project name "${projectName}-" (total: ${combined.length} chars). ` +
`Shorten the target name to ${maxTargetLen} characters or fewer.`
);
}
}
}
}

/**
* Validates that Container agents have required Dockerfiles.
*/
Expand Down
12 changes: 6 additions & 6 deletions src/schema/schemas/primitives/__tests__/http-gateway.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,12 +22,12 @@ describe('HttpGatewayNameSchema', () => {
expect(HttpGatewayNameSchema.safeParse('my_gateway').success).toBe(false);
});

it('rejects name over 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(49)).success).toBe(false);
it('accepts name longer than 24 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(25)).success).toBe(true);
});

it('accepts name at 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(48)).success).toBe(true);
it('accepts name at 47 chars (room for 1-char project name + hyphen)', () => {
expect(HttpGatewayNameSchema.safeParse('a' + 'b'.repeat(46)).success).toBe(true);
});
});

Expand DownExpand Up@@ -60,8 +60,8 @@ describe('HttpGatewaySchema', () => {
expect(HttpGatewaySchema.safeParse(withoutRuntimeRef).success).toBe(false);
});

it('rejects name too long (>48 chars)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a'.repeat(49) }).success).toBe(false);
it('accepts name longer than 24 chars (no standalone max cap)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a' + 'b'.repeat(30) }).success).toBe(true);
});

it('rejects name starting with number', () => {
Expand Down
5 changes: 2 additions & 3 deletions src/schema/schemas/primitives/http-gateway.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,9 @@ import { z } from 'zod';
export const HttpGatewayNameSchema = z
.string()
.min(1, 'Name is required')
.max(48)
.regex(
/^[a-zA-Z][a-zA-Z0-9-]{0,47}$/,
'Must begin with a letter and contain only alphanumeric characters and hyphens (max 48 chars)'
Comment thread
jariy17 marked this conversation as resolved.
/^[a-zA-Z][a-zA-Z0-9-]*$/,
'Gateway name must start with a letter and contain only alphanumeric characters or hyphens (combined with project name must fit 48-char AWS limit)'
);

export const HttpGatewayTargetSchema = z.object({
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,13 +139,13 @@ describe('setupHttpGateways', () => {

expect(mockCreateHttpGateway).toHaveBeenCalledWith({
region: 'us-east-1',
name: 'MyHttpGw',
name: 'TestProject-MyHttpGw',
roleArn: 'arn:aws:iam::123456789012:role/ExistingRole',
});
expect(mockCreateHttpGatewayTarget).toHaveBeenCalledWith({
region: 'us-east-1',
gatewayId: 'gw-001',
targetName: 'my-agent',
targetName: 'TestProject-my-agent',
runtimeArn: 'arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/rt-123',
});
});
Expand DownExpand Up@@ -175,7 +175,7 @@ describe('setupHttpGateways', () => {

it('finds gateway by name via list (state loss recovery)', async () => {
mockListAllHttpGateways.mockResolvedValue([
{ name: 'MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
{ name: 'TestProject-MyHttpGw', gatewayId: 'gw-api', gatewayArn: 'arn:httpgw:api' },
]);

const result = await setupHttpGateways({
Expand All@@ -190,6 +190,39 @@ describe('setupHttpGateways', () => {
expect(mockCreateHttpGateway).not.toHaveBeenCalled();
});

it('recovers state using legacy (pre-migration) gateway name when prefixed name not found', async () => {
// First call: prefixed name "TestProject-MyHttpGw" → not found
// Second call: unprefixed legacy name "MyHttpGw" → found
mockListAllHttpGateways
.mockResolvedValueOnce([])
.mockResolvedValueOnce([{ name: 'MyHttpGw', gatewayId: 'gw-legacy', gatewayArn: 'arn:httpgw:legacy' }]);

const warnSpy = vi.spyOn(console, 'warn').mockReturnValue(undefined);

const result = await setupHttpGateways({
region: 'us-east-1',
projectName: 'TestProject',
projectSpec: makeProjectSpec([sampleHttpGateway]),
deployedResources: sampleDeployedResources,
});

// findHttpGatewayByName was called twice: once for prefixed, once for unprefixed name
expect(mockListAllHttpGateways).toHaveBeenCalledTimes(2);

// Gateway result is skipped (not created)
expect(result.results[0]!.status).toBe('skipped');
expect(result.results[0]!.gatewayId).toBe('gw-legacy');
expect(result.httpGateways.MyHttpGw!.gatewayId).toBe('gw-legacy');

// createHttpGateway was NOT called
expect(mockCreateHttpGateway).not.toHaveBeenCalled();

// console.warn was called with the pre-migration warning text
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('pre-migration name'));

warnSpy.mockRestore();
});

it('reports error on missing runtime ref', async () => {
const emptyDeployedResources = {} as unknown as DeployedResourceState;

Expand Down
45 changes: 45 additions & 0 deletions src/cli/operations/deploy/__tests__/preflight.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -126,6 +126,51 @@ describe('validateProject', () => {
expect(result.projectSpec.name).toBe('test-project');
expect(result.isTeardownDeploy).toBe(false);
});

it('rejects gateway target name that exceeds 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (39) = 49 > 48
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(39), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

await expect(validateProject()).rejects.toThrow(
'HTTP gateway target "' + 'a'.repeat(39) + '" in gateway "gw" would exceed the 48-character AWS limit'
);
});

it('accepts gateway target name within 48 chars when prefixed with project name', async () => {
mockRequireConfigRoot.mockReturnValue('/project/agentcore');
mockValidate.mockReturnValue(undefined);
// projectName "myproject" (9) + "-" (1) + targetName (38) = 48 == limit
mockReadProjectSpec.mockResolvedValue({
name: 'myproject',
runtimes: [],
httpGateways: [
{
name: 'gw',
targets: [{ name: 'a'.repeat(38), runtimeRef: 'rt', qualifier: 'DEFAULT' }],
},
],
agentCoreGateways: [{ name: 'gw' }],
});
mockReadAWSDeploymentTargets.mockResolvedValue([]);
mockValidateAwsCredentials.mockResolvedValue(undefined);

const result = await validateProject();
expect(result.projectSpec.name).toBe('myproject');
});
});

describe('formatError', () => {
Expand Down
25 changes: 21 additions & 4 deletions src/cli/operations/deploy/post-deploy-ab-tests.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -142,7 +142,7 @@ export async function setupABTests(options: SetupABTestsOptions): Promise<SetupA
const existingTest = existingABTests?.[testSpec.name];

// Resolve ARN references from deployed state
const resolvedVariants = resolveVariants(testSpec.variants, deployedResources);
const resolvedVariants = resolveVariants(testSpec.variants, projectSpec.name, deployedResources);
Comment thread
jariy17 marked this conversation as resolved.
const resolvedGatewayArn = resolveGatewayArn(testSpec.gatewayRef, deployedResources);
if (!resolvedGatewayArn.startsWith('arn:') || resolvedGatewayArn.split(':').length < 6) {
results.push({
Expand DownExpand Up@@ -409,7 +409,8 @@ async function findABTestByName(
/**
* Resolve variant config bundle references.
* If bundleArn is a name (not an ARN), look it up in deployed config bundles.
* Target-based variants are passed through as-is.
* Target-based variants have their target name prefixed with projectName to match
* what post-deploy-http-gateways.ts creates on AWS (e.g. `${projectName}-${tgt.name}`).
Comment thread
jariy17 marked this conversation as resolved.
*/
function resolveVariants(
variants: {
Expand All@@ -420,6 +421,7 @@ function resolveVariants(
target?: { targetName: string };
};
}[],
projectName: string,
deployedResources?: DeployedResourceState
): ABTestVariant[] {
return variants.map(v => {
Expand All@@ -436,12 +438,15 @@ function resolveVariants(
},
};
}
// Target-based variant — pass through
// Target-based variant — prepend projectName to match the AWS-side name created by
// post-deploy-http-gateways.ts: `${projectName}-${tgt.name}`
return {
name: v.name,
weight: v.weight,
variantConfiguration: {
...(v.variantConfiguration.target && { target: { name: v.variantConfiguration.target.targetName } }),
...(v.variantConfiguration.target && {
target: { name: resolveTargetName(v.variantConfiguration.target.targetName, projectName) },
}),
},
};
});
Expand DownExpand Up@@ -475,6 +480,18 @@ function resolveConfigBundleVersion(
return versionRef;
}

/**
* Resolve a variant target name, applying the project prefix if not already present.
* This handles legacy configs that were created before the prefix requirement.
*/
function resolveTargetName(targetName: string, projectName: string): string {
// If the target name already starts with the project prefix, use as-is to avoid double-prefixing
if (targetName.startsWith(`${projectName}-`)) {
return targetName;
}
return `${projectName}-${targetName}`;
}

function resolveGatewayArn(ref: string, deployedResources?: DeployedResourceState): string {
if (ref.startsWith('arn:')) return ref;

Expand Down
36 changes: 30 additions & 6 deletions src/cli/operations/deploy/post-deploy-http-gateways.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

for (const tgt of gwSpec.targets) {
const existingTarget = existingTargetsByName.get(tgt.name);
const existingTarget = existingTargetsByName.get(`${projectName}-${tgt.name}`);
if (existingTarget) {
// Target exists by name — check if qualifier matches
try {
Expand DownExpand Up@@ -143,7 +143,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: existingGateway.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand All@@ -170,7 +170,8 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
}

// Try to find by name via list (handles re-creation after state loss)
const existingByName = await findHttpGatewayByName(region, gwSpec.name);
const prefixedGatewayName = `${projectName}-${gwSpec.name}`;
const existingByName = await findHttpGatewayByName(region, prefixedGatewayName);
if (existingByName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" found by name but local state was lost. Target and role state may be incomplete — consider re-deploying.`
Expand All@@ -189,6 +190,29 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
continue;
}

// Migration fallback: try unprefixed name for pre-PR gateways (Comment 3 fix)
const existingByLegacyName = await findHttpGatewayByName(region, gwSpec.name);
if (existingByLegacyName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" was found using its pre-migration name. ` +
`This CLI version uses the naming convention "${prefixedGatewayName}". ` +
`The gateway has been recovered from state loss. ` +
`You may want to rename "${gwSpec.name}" to "${prefixedGatewayName}" on AWS to match the new convention.`
);
httpGateways[gwSpec.name] = {
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
// targetId, roleArn, roleCreatedByCli unknown after state-loss recovery
};
results.push({
gatewayName: gwSpec.name,
status: 'skipped',
gatewayId: existingByLegacyName.gatewayId,
gatewayArn: existingByLegacyName.gatewayArn,
});
continue;
}

// Resolve runtime ARN from deployed state
const runtimeState = deployedResources?.runtimes?.[gwSpec.runtimeRef];
if (!runtimeState) {
Expand DownExpand Up@@ -216,7 +240,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
// Creating HTTP gateway for runtime
const createResult = await createHttpGateway({
region,
name: gwSpec.name,
name: `${projectName}-${gwSpec.name}`,
roleArn: resolvedRoleArn,
});

Expand All@@ -231,7 +255,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const targetResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: gwSpec.runtimeRef,
targetName: `${projectName}-${gwSpec.runtimeRef}`,
runtimeArn,
});

Expand DownExpand Up@@ -288,7 +312,7 @@ export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Prom
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: tgt.name,
targetName: `${projectName}-${tgt.name}`,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
Expand Down
34 changes: 34 additions & 0 deletions src/cli/operations/deploy/preflight.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,7 @@ export function formatError(err: unknown): string {
* Returns the project context needed for subsequent steps.
*/
const MAX_RUNTIME_NAME_LENGTH = 48;
const MAX_GATEWAY_COMBINED_NAME_LENGTH = 48;

export async function validateProject(): Promise<PreflightContext> {
// Find the agentcore config directory, walking up from cwd if needed
Expand DownExpand Up@@ -108,6 +109,9 @@ export async function validateProject(): Promise<PreflightContext> {
// Validate runtime names don't exceed AWS limits
validateRuntimeNames(projectSpec);

// Validate HTTP gateway names don't exceed AWS limits when combined with project name
validateHttpGatewayNames(projectSpec);

// Validate Container agents have Dockerfiles
validateContainerAgents(projectSpec, configRoot);

Expand DownExpand Up@@ -140,6 +144,36 @@ function validateRuntimeNames(projectSpec: AgentCoreProjectSpec): void {
}
}

/**
* Validates that combined HTTP gateway names (projectName-gatewayName) don't exceed AWS limits.
*/
function validateHttpGatewayNames(projectSpec: AgentCoreProjectSpec): void {
const projectName = projectSpec.name;
for (const gateway of projectSpec.httpGateways ?? []) {
const gwName = gateway.name;
if (gwName) {
const combinedName = `${projectName}-${gwName}`;
if (combinedName.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
throw new Error(
`HTTP gateway name too long: "${combinedName}" (${combinedName.length} chars). ` +
`AWS limits gateway names to ${MAX_GATEWAY_COMBINED_NAME_LENGTH} characters. ` +
`Shorten the project name or gateway name in agentcore.json.`
);
}
}
for (const target of gateway.targets ?? []) {
const combined = `${projectName}-${target.name}`;
if (combined.length > MAX_GATEWAY_COMBINED_NAME_LENGTH) {
const maxTargetLen = MAX_GATEWAY_COMBINED_NAME_LENGTH - projectName.length - 1;
throw new Error(
`HTTP gateway target "${target.name}" in gateway "${gwName}" would exceed the ${MAX_GATEWAY_COMBINED_NAME_LENGTH}-character AWS limit when prefixed with project name "${projectName}-" (total: ${combined.length} chars). ` +
`Shorten the target name to ${maxTargetLen} characters or fewer.`
);
}
}
}
}

/**
* Validates that Container agents have required Dockerfiles.
*/
Expand Down
12 changes: 6 additions & 6 deletions src/schema/schemas/primitives/__tests__/http-gateway.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,12 +22,12 @@ describe('HttpGatewayNameSchema', () => {
expect(HttpGatewayNameSchema.safeParse('my_gateway').success).toBe(false);
});

it('rejects name over 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(49)).success).toBe(false);
it('accepts name longer than 24 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(25)).success).toBe(true);
});

it('accepts name at 48 chars', () => {
expect(HttpGatewayNameSchema.safeParse('a'.repeat(48)).success).toBe(true);
it('accepts name at 47 chars (room for 1-char project name + hyphen)', () => {
expect(HttpGatewayNameSchema.safeParse('a' + 'b'.repeat(46)).success).toBe(true);
});
});

Expand DownExpand Up@@ -60,8 +60,8 @@ describe('HttpGatewaySchema', () => {
expect(HttpGatewaySchema.safeParse(withoutRuntimeRef).success).toBe(false);
});

it('rejects name too long (>48 chars)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a'.repeat(49) }).success).toBe(false);
it('accepts name longer than 24 chars (no standalone max cap)', () => {
expect(HttpGatewaySchema.safeParse({ ...validHttpGateway, name: 'a' + 'b'.repeat(30) }).success).toBe(true);
});

it('rejects name starting with number', () => {
Expand Down
5 changes: 2 additions & 3 deletions src/schema/schemas/primitives/http-gateway.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,10 +7,9 @@ import { z } from 'zod';
export const HttpGatewayNameSchema = z
.string()
.min(1, 'Name is required')
.max(48)
.regex(
/^[a-zA-Z][a-zA-Z0-9-]{0,47}$/,
'Must begin with a letter and contain only alphanumeric characters and hyphens (max 48 chars)'
Comment thread
jariy17 marked this conversation as resolved.
/^[a-zA-Z][a-zA-Z0-9-]*$/,
'Gateway name must start with a letter and contain only alphanumeric characters or hyphens (combined with project name must fit 48-char AWS limit)'
);

export const HttpGatewayTargetSchema = z.object({
Expand Down
Loading