🧭 Navigation:
Home | Vision LLM Theory | UI | 🔵 Deployment | CDK Stacks | Runtime | S3 Files | Lambda Specialists | Prompting System
Step-by-step AWS CDK deployment for BADGERS. For architecture overview and technical details, see the main README.
| Service | Purpose |
|---|---|
| Amazon Bedrock AgentCore | Runtime + Gateway for agent orchestration |
| Amazon Bedrock | Claude foundation model access |
| AWS Lambda | Serverless specialist functions |
| Amazon S3 | Configuration and output storage |
| Amazon DynamoDB | Job and subtask state tracking |
| Amazon Cognito | OIDC/PKCE for the UI, OAuth 2.0 M2M for the Gateway |
| Amazon ECS | UI hosting on an Express Gateway service |
| Amazon VPC | Private networking and VPC endpoints for the UI |
| Amazon ECR | Container image registry |
| AWS Secrets Manager | Credential storage |
| AWS SSM Parameter Store | Configuration parameters |
| Amazon CloudWatch | Logging and observability |
| AWS X-Ray | Distributed tracing |
Verify your environment:
aws --version # AWS CLI cdk --version # AWS CDK v2 docker info # Docker running python --version # Python 3.12+ uv --version # uv package manager
Important
Docker must be running before deployment. Lambda layers and the Runtime container require Docker to build.
Warning
Academic/Research Deployments: If your users process documents with sensitive, inflammatory, or offensive content (common in academic research), you must configure the operating environment before use. Edit s3_files/agent_config/agent_operating_environment_config.json and sync to S3. Without this, the model may refuse to extract or omit sensitive content. See S3 Files → Operating Environment Configuration for details. For production deployments, we recommend moving this value to AWS Secrets Manager for added security.
Two values identify a deployment:
DEPLOYMENT_ID— a short label you choose (dev,demo,b2). Must match^[a-z][a-z0-9-]{0,15}$: lowercase, starting with a letter, 16 characters or fewer. It ends up in S3 bucket names, which is why uppercase is rejected.STACK_SUFFIX— three random hex characters, generated once perDEPLOYMENT_ID.
Both are persisted in .deploy-state/{DEPLOYMENT_ID}.json and appear in every name:
| Pattern | Example | |
|---|---|---|
| Stack names | BADGERS-{Name}-{DEPLOYMENT_ID}-{suffix} |
BADGERS-S3-dev-a1b |
| Resource names | badgers-{kind}-{id}-{suffix} |
badgers-config-dev-a1b |
| SSM prefix | /badgers-{id}-{suffix} |
/badgers-dev-a1b/jobs-table-name |
Stack names carry the deployment id as well as the suffix so that each stack is
self-describing. The suffix alone would be enough to keep names unique, but not enough to
establish identity — with suffix-only names, a mistyped DEPLOYMENT_ID still resolves
real stacks while every resource name derived from it points at something that does not
exist. Tooling can now read a deployment's identity straight off the stack name.
Anything running cdk directly needs both values:
DEPLOYMENT_ID=dev STACK_SUFFIX=a1b uv run cdk deploy BADGERS-S3-dev-a1b
# or as context
uv run cdk deploy -c deployment_id=dev -c stack_suffix=a1b BADGERS-S3-dev-a1bapp.py fails fast with usage if either is missing, rather than inventing a suffix and
deploying a second copy of everything by accident.
AgentCore runtime and memory names must match
[a-zA-Z][a-zA-Z0-9_]{0,47}and cannot contain hyphens, so those two stacks normalise the composite id to underscores —badgers_runtime_ws_dev_a1b,badgers_memory_dev_a1b.
From the repository root:
./deploy.sh
That is the whole command. deploy.sh does not read DEPLOYMENT_ID from the
environment — it unsets it and always asks, because a value left exported in your shell
silently targets another deployment's stacks and state file.
On start it scans .deploy-state/ and offers what it finds:
Deployments found — most recent activity first:
1) dev 8/9 steps in progress last activity 2026-08-04T16:14:38Z
2) demo 9/9 steps complete last activity 2026-08-02T11:02:10Z
n) Start a new deployment instead
Select which? (1-2, or n) [1]:
Complete and in-progress deployments are both listed, so you can re-run a single step
against a finished deployment. Choosing n prompts for a new id and rejects one that
already has state — pick it from the list instead. Pressing Enter takes the most recent.
Then the menu:
| Option | Step | What it does |
|---|---|---|
1 |
Build Lambda Layers | foundation, PDF processing, poppler/qdf archives |
2 |
Foundational Infra | S3, Cognito, DynamoDB, IAM, ECR, Inference Profiles, XRay, Memory, VPC |
3 |
Upload Prompts, Manifests & Schemas | syncs s3_files/ to the config bucket |
4 |
Specialist Lambdas | container images to ECR, then the Lambda stack |
5 |
Gateway | AgentCore MCP Gateway with Lambda targets |
6 |
Runtime — Build & Deploy | builds/pushes the agent image, deploys the Runtime |
7 |
UI — Build & Push Image | generates ui/.env, builds the Vite bundle and image, pushes |
8 |
UI — Deploy ECS | deploys the ECS stack, forces the image rollout, waits |
9 |
Full Deployment | runs 1 → 8 in order, stopping at the first failure |
r |
Resume | runs only the steps still outstanding, without prompting on each |
10 |
Show Deployment Status | current suffix, per-step completion with timestamps |
11 |
Reset Deployment State | marks all steps incomplete; deletes nothing in AWS |
m |
Models | prints the model registry and which steps a registry edit requires |
0 |
Exit |
You can also run one directly — ./deploy.sh 8 or ./deploy.sh resume — but the
deployment is still chosen interactively first.
Both get you to a complete deployment; they differ in friction.
Option 9 walks all eight steps. Steps already marked complete stop and ask whether to re-run, so resuming from step 4 costs you three prompts. Declining a prompt is treated as success and the run continues.
Option r skips completed steps before calling them, so those prompts never fire. It
starts at the first outstanding step. A step counts as complete only when every state key
it writes is set, so an interrupted step 6 (image pushed, runtime not deployed) is
re-entered rather than skipped.
BADGERS_ASSUME_YES=1 answers every confirmation with yes, for unattended runs. Note it
re-runs completed steps rather than skipping them — it is not a quiet resume.
Each step records completion in .deploy-state/{DEPLOYMENT_ID}.json with a timestamp, so
a re-run after a failure continues rather than starting over. Every step is idempotent.
If step 8 fails, ui_image_pushed is cleared deliberately: an ECS rollout almost always
fails because of something inside the image, and redeploying the stack alone will not pick
up a code change. Resume therefore rebuilds and pushes in step 7 before retrying step 8.
When the cause was outside the image — a quota, a permission — step 7 is a no-op rebuild
that costs only time.
See DEPLOYMENT_SCRIPTS.md for every script and its flags.
The targeted region-inspection workflow spans the configuration bucket, specialist Lambdas,
AgentCore Gateway, AgentCore Runtime prompts, and the report UI. For an existing deployment,
run steps 3 through 8 in order:
- Step 3 uploads the region-inspector manifest, schema, shared uncertainty prompt, and correlation rules.
- Step 4 deploys the
region_inspectorLambda and the report-materialization changes. - Step 5 reconciles the
inspect_region_toolGateway target. - Step 6 deploys the runtime workflow that triggers inspection and passes its result to correlation.
- Steps 7 and 8 rebuild and deploy the UI so the Page Reader exposes inspection cards and crop images.
The workflow is conditional: specialists must first flag a localized uncertainty. A deployment can contain the tool without producing inspection artifacts for every report.
13 stacks deployed in dependency order, plus 1 optional. See CDK Stacks for details and the dependency graph.
| Stack | Purpose |
|---|---|
BADGERS-S3-{id}-{suffix} |
Config bucket (manifests/prompts) + source + output buckets |
BADGERS-Cognito-{id}-{suffix} |
User pool with UI (OIDC/PKCE) and Gateway (M2M) clients |
BADGERS-DynamoDB-{id}-{suffix} |
Jobs table for doc/job/subtask tracking |
BADGERS-IAM-{id}-{suffix} |
Lambda execution role with Bedrock/S3/DynamoDB permissions |
BADGERS-ECR-{id}-{suffix} |
Container registry for agent and container Lambda images |
BADGERS-InferenceProfiles-{id}-{suffix} |
Application Inference Profiles for cost tracking |
BADGERS-Lambda-{id}-{suffix} |
Base specialist functions + foundation layer |
BADGERS-XRay-{id}-{suffix} |
X-Ray Transaction Search (account-level singleton, often skipped) |
BADGERS-Gateway-{id}-{suffix} |
AgentCore MCP Gateway with Lambda targets |
BADGERS-Memory-{id}-{suffix} |
AgentCore Memory for session persistence |
BADGERS-RuntimeWebSocket-{id}-{suffix} |
AgentCore Runtime (Strands agent with WebSocket) |
BADGERS-Vpc-{id}-{suffix} |
VPC with public/private subnets, NAT, flow logs, VPC endpoints |
BADGERS-ECS-{id}-{suffix} |
Unified UI on an ECS Express Gateway service |
BADGERS-CustomSpecialists-{id}-{suffix} |
Custom specialists (optional, wizard-created) |
The XRay stack enables X-Ray Transaction Search, which is an account-and-region
singleton and needs a CloudWatch Logs resource policy. That policy competes for a hard
quota of 10 per region (Service Quotas code L-89892494), which is not
adjustable — a support request will not raise it — and is shared with every other
project in the account.
deploy.sh resolves this before any cdk deploy runs, in all five stack-deploying steps:
- Already ACTIVE → the XRay stack is dropped from the app entirely. Nothing to enable, and skipping it avoids consuming a policy slot for a setting that is already on.
- Not enabled, room in the quota → the stack deploys and enables it.
- Not enabled, quota full → the deploy is refused before anything is created, and the
existing policies are listed with what each one grants, so you can decide what to
reclaim. Left unchecked, CloudFormation fails mid-deploy with a bare
ServiceLimitExceededafter other stacks already exist.
Set BADGERS_SKIP_XRAY=1 to skip tracing regardless. This matters because
RuntimeWebSocket depends on the XRay stack and cdk deploy includes a stack's
dependencies — so deploying the Runtime or ECS stack with the decision unresolved would
quietly pull XRay back in.
The UI runs on BADGERS-Vpc-{id}-{suffix} + BADGERS-ECS-{id}-{suffix}. The ECS Express
Gateway service provisions and manages its own load balancer and HTTPS endpoint, so no
hosted zone, domain, or ACM certificate is required — there is nothing to configure
before deploying it.
Cognito values must be baked into the Vite bundle at build time, so ordering matters.
deploy.sh steps 7 and 8 handle it:
./deploy.sh 7 # generate ui/.env, build the bundle, build and push the image ./deploy.sh 8 # deploy the ECS stack, force the rollout, wait for it
Step 8 prompts before doing anything:
UI network exposure — fixed for the life of this VPC.
y) Public internet-facing load balancer; tasks get public IPs.
n) Internal internal load balancer; reachable only from inside the VPC.
Make the UI publicly accessible? (y/n) [y]:
ECS Express Mode derives the load balancer scheme from the subnets it is given: public
subnets produce an internet-facing ALB, subnets without an internet gateway produce an
internal one. The first Express service in a VPC establishes that scheme for the VPC,
so answering differently later does not flip an existing load balancer — you would have to
destroy the ECS and VPC stacks and redeploy. Answer n and the public
https://<id>.ecs.<region>.on.aws URL will resolve but never respond.
The prompt is asked up front for options 9 and 12 so the rest of the run is unattended.
UI_PUBLIC_ACCESS=true|false in the environment is honoured without prompting.
The stack references the UI image by a static tag (:frontend). Pushing a new image to
that tag leaves the CloudFormation template unchanged, so cdk deploy would report no
changes and the service would keep serving the old image. Step 8 therefore calls
update-express-gateway-service with the container spec after the cdk deploy, forcing a
new deployment regardless, then polls rolloutState until COMPLETED. That is what makes
a step 7 rebuild actually take effect.
Step 7 runs scripts/generate_ui_env.sh first, because a bundle built before Cognito
exists has no authority or client id compiled into it and falls back to the server's
local-dev bypass.
BADGERS-ECS-{id}-{suffix} reads all container configuration from SSM Parameter Store under
/badgers-{id}-{suffix}/, so there is no .env to ship into the image beyond the
build-time VITE_* values.
Note:
scripts/generate_ui_env.shalso writes the local-development runtime values (buckets, Runtime ARN, Gateway ID, jobs table) into the sameui/.env. Vite ignores the non-VITE_lines,ui/server/index.jsreads them when run outside ECS, and the deployed service reads everything from SSM.
Prefer ./deploy.sh — it does all of this with resumable state. The steps below are for
when you need to drive a single stack yourself.
Every command assumes the deployment identity is exported, and {suffix} below stands for
your actual suffix from .deploy-state/{DEPLOYMENT_ID}.json:
export DEPLOYMENT_ID=dev export STACK_SUFFIX=a1b
From the repository root. The CDK app's dependencies are declared in the root
pyproject.toml and pinned in uv.lock; uv sync installs exactly that set, and every
cdk command below runs as uv run cdk against it.
uv sync
All layer build scripts must be run from the deployment/lambdas directory.
cd lambdas ./build_foundation_layer.sh # Core framework, boto3, pillow ./build_poppler_qdf_layer.sh # PDF rendering (pdftoppm, pdfinfo) cd ..
| Script | Output | Purpose | Used By |
|---|---|---|---|
build_foundation_layer.sh |
layer.zip |
Core specialist framework, AWS SDK, Pillow | All Lambda specialists |
build_poppler_qdf_layer.sh |
poppler-qpdf-layer.zip |
Poppler binaries for PDF→image conversion | pdf_to_images_converter |
build_container_lambdas.sh |
ECR images | Container images for complex specialists | image_enhancer, remediation_specialist |
Note:
build_enhancement_layer.shis retained on disk but no longer deployed. Image enhancement runs in the container-basedimage_enhancerLambda which bundles its own dependencies.v5.0.3: The former PDF-processing layer is no longer built or deployed. It was not attached to any v5 Lambda, but CDK still tried to create it. A newer transitive PyMuPDF dependency set could exceed Lambda's uncompressed layer limit and block an otherwise valid deployment.
Container-based Lambdas (for functions exceeding layer size limits) are built separately:
cd lambdas ./build_container_lambdas.sh <deployment_id> cd ..
This builds and pushes Docker images to ECR for image_enhancer and remediation_specialist.
./deploy.sh 1 runs all the layer builds in the correct order. Manual builds are only needed for:
- Partial redeployments
- Layer updates without full redeploy
- Troubleshooting build issues
uv run cdk bootstrap
Tip
New to CDK? See the AWS CDK Developer Guide for installation and concepts.
No alpha CDK modules are required. The AgentCore Gateway, Runtime, and Memory constructs
come from aws_cdk.aws_bedrockagentcore
in aws-cdk-lib (2.263.0 or later), which is what uv sync installs.
Same set and order as deploy.sh step 2. IAM imports the DynamoDB table and the S3
buckets, Lambda imports ECR and the inference profiles, so the order below is not
optional. The manual path skips the two Bedrock model preflights deploy.sh runs here; if
a model is not reachable from your account you find out from a specialist's
AccessDeniedException instead.
for s in S3 Cognito DynamoDB IAM ECR InferenceProfiles Memory Vpc; do uv run cdk deploy BADGERS-${s}-{id}-{suffix} --require-approval never done uv run cdk deploy BADGERS-XRay-{id}-{suffix} --require-approval never # optional; see X-Ray section # Sync s3_files/ (prompts, manifests, schemas, agent config, model registry) ./sync_s3_files.sh
The Lambda stack references the two container images by tag, so they must be in ECR before
it deploys. build_container_lambdas.sh takes the resource id ({id}-{suffix}).
cd lambdas && ./build_container_lambdas.sh {id}-{suffix} && cd .. uv run cdk deploy BADGERS-Lambda-{id}-{suffix} --require-approval never
uv run cdk deploy BADGERS-Gateway-{id}-{suffix} --require-approval nevercd runtime && ./build_and_push_websocket.sh && cd .. uv run cdk deploy BADGERS-RuntimeWebSocket-{id}-{suffix} --require-approval never
generate_ui_env.sh must run after Cognito exists — the bundle compiles the authority and
client id in. The image is linux/amd64, matching the Express Gateway service.
bash scripts/generate_ui_env.sh (cd ../ui && npm install && npm run build) aws ecr get-login-password --region {region} | docker login --username AWS --password-stdin {account}.dkr.ecr.{region}.amazonaws.com docker build --platform linux/amd64 --file ../ui/Dockerfile --tag {ecr-repo-uri}:frontend ../ui docker push {ecr-repo-uri}:frontend uv run cdk deploy BADGERS-ECS-{id}-{suffix} --require-approval never
The ECS stack pins the frontend tag, so pushing a new image later leaves the template
unchanged; deploy.sh step 8 forces the rollout with update-express-gateway-service
afterwards, and a manual redeploy has to do the same.
Key outputs after deployment:
| Output | Stack | Description |
|---|---|---|
GatewayUrl / GatewayId |
Gateway | MCP endpoint for tool invocation |
RuntimeArn / RuntimeId |
RuntimeWebSocket | AgentCore Runtime the UI opens its WebSocket to |
UserPoolId / UserPoolClientId / UIClientId |
Cognito | Cognito authentication (Gateway M2M and UI OIDC) |
ConfigBucketName / SourceBucketName / OutputBucketName |
S3 | Config, upload, and results buckets |
MemoryId |
Memory | AgentCore Memory ID |
ServiceUrl |
ECS | The UI |
deployment/
├── app.py # 🎯 CDK app entry point
├── scripts/common.sh # 🔗 Shared logging, state, stack-name and CDK helpers
├── deploy_specialist.sh # 🔬 Single specialist deployment
├── deploy_custom_specialists.sh # 🎨 Wizard-created specialist deployment
├── scripts/
│ └── generate_ui_env.sh # 🔐 Writes ui/.env (VITE_* Cognito + local runtime values) from stack outputs
├── stacks/ # 📦 CDK stack definitions
├── lambdas/
│ ├── build_foundation_layer.sh # Core framework layer
│ ├── build_poppler_qdf_layer.sh # PDF rendering layer
│ ├── build_enhancement_layer.sh # Image enhancement layer (UNUSED - retained for reference)
│ ├── build_container_lambdas.sh # Container image builder
│ ├── deploy_foundation_layer.sh # Manual layer deployment
│ ├── deploy_poppler_layer.sh # Manual layer deployment
│ ├── containers/ # 🐳 Container Lambda Dockerfiles
│ └── code/ # ⚡ 25 specialist/utility functions (+2 containers); deployment_config.json picks which deploy
├── runtime/ # 🐳 AgentCore container
│ ├── Dockerfile.websocket
│ ├── build_and_push_websocket.sh
│ └── agent/main-websocket.py
├── s3_files/ # ☁️ S3 configuration
│ ├── manifests/
│ ├── prompts/
│ ├── schemas/
│ └── wrappers/
├── badgers-foundation/ # 🏗️ Shared specialist framework (used by non-container specialists and image_enhancer)
Each specialist has a manifest file in s3_files/manifests/ that configures its behavior. A manifest names models only — never a transport, an endpoint, or a provider. Everything else about a model lives in s3_files/config/model_registry.json, so a manifest cannot contradict what is deployed.
Every entry must name a model that is active in the registry. foundation/model_selection.py is the single parser for this block, and it raises rather than defaulting: a silently defaulted model ID is how a specialist ends up invoking something nobody chose.
The verbose form, one object per model, carries per-model reasoning settings:
{
"specialist": {
"name": "correlation_specialist",
"model_selections": {
"primary": {
"model_id": "us.anthropic.claude-sonnet-4-6",
"adaptive_thinking": true,
"effort": "high"
},
"fallback_list": [
{
"model_id": "us.openai.gpt-5.6-terra",
"extended_thinking": false
},
{
"model_id": "us.amazon.nova-2-lite-v1:0",
"extended_thinking": true,
"budget_tokens": 4000
}
]
}
}
}| Field | Description |
|---|---|
model_id |
A model ID that is active in the registry. Required |
extended_thinking |
Request a fixed thinking budget. Needs a model whose registry thinking is "extended" |
budget_tokens |
Max tokens for thinking content. Read when extended_thinking is true |
adaptive_thinking |
Let the model choose its own reasoning depth. Needs registry thinking of "adaptive" |
effort |
low, medium, or high. Defaults to high. An unknown value is rejected at parse time |
expected_output_tokens |
Estimated output tokens for cost calculation (in the specialist section) |
audit_mode |
Boolean in inputSchema — enables confidence scoring and review flags |
The bare-string form carries no reasoning settings, and 23 of the 24 built-in manifests that
carry model_selections use it (image_enhancer takes its model from VISION_MODEL and
html_report_specialist is deterministic, so neither has the block; the one exception is
correlation_specialist, whose fallback entry is an object):
"model_selections": { "primary": "us.anthropic.claude-sonnet-4-6", "fallback_list": ["us.openai.gpt-5.6-terra", "us.amazon.nova-2-lite-v1:0"] }
Note
Thinking support is a property of the model, recorded in the registry's thinking field as null, "extended", or "adaptive". Claude Opus 5 also carries thinking_default_on: its adaptive thinking is on unless a request disables it, so the runtime treats every Opus 5 call as a thinking call and pins temperature to 1. The four OpenAI models document no reasoning parameter and take thinking: null.
When thinking is active, the content is saved to S3 alongside results: {session_id}/{specialist_name}/{image}_thinking_{timestamp}.txt. Nova 2 returns [REDACTED] reasoning content — expected, and still billed.
Warning
Setting effort: "high" on a Nova model omits the output-token bound entirely, because Nova's highest reasoning effort requires temperature and maxTokens to be unset. AWS documents output reaching 128K tokens on that path. Use medium unless you want that.
BADGERS uses Application Inference Profiles to enable cost allocation and usage monitoring per model. inference_profiles_stack.py creates one trackable profile per model in s3_files/config/model_registry.json, each wrapping that model's US geo cross-Region system-defined profile (us.*).
- CDK reads the registry at synth and creates one profile per provisioned model
- The same loop writes SSM
/badgers-{deployment_id}/model-profiles— a model ID → profile ARN map - At invocation time,
bedrock_client.pyreads that parameter once and caches it, then resolves the model ID to a profile ARN - Bedrock is invoked using the profile ARN instead of the raw model ID
There are no per-model *_PROFILE_ARN environment variables. Every consumer reads the one SSM parameter, whose name arrives as MODEL_PROFILES_PARAM. Adding or removing a model is a registry edit plus a deploy; no stack lists models by hand.
Profiles are named badgers-{model}-{deployment_id} — for example badgers-claude-sonnet-4-6-abc12345.
Note
If no inference profile is configured for a model ID, the system falls back to using the model ID directly. This allows local development without deployed profiles.
Model inference does not stay in your deployment Region. This surprises people, so it is worth being explicit.
Every Converse model BADGERS ships except Qwen3 VL 235B is invoked through a US geo cross-Region inference profile (us.anthropic.…, us.amazon.…, us.openai.…, us.moonshotai.…, us.mistral.…). Geo cross-Region inference means Bedrock picks a destination Region within the US geography to process each request. Your deployment Region is the source Region; it is not necessarily where the tokens are processed.
For the models whose cards publish a destination table (Sonnet 4.6, Opus 4.6, Nova 2 Lite, Pixtral Large), a source Region of us-west-2 routes to us-east-1, us-east-2, or us-west-2. The rest document a us.* profile without publishing a destination list.
Gemma 4 31B is one exception. It is served only on the OpenAI-compatible bedrock-mantle endpoint (https://bedrock-mantle.{region}.api.aws/openai/v1), not Converse, and has no inference profile. The foundation layer signs an OpenAI Chat Completions request with SigV4 (service bedrock-mantle) and cost is attributed to the Bedrock default project rather than a us.* profile. Its regional behavior follows the mantle endpoint, not a us.* cross-Region profile.
Qwen3 VL 235B is the other exception. It uses Converse like the rest, but its model card lists Geo and Global cross-Region inference as Not supported, so there is no us.* system profile to wrap. Its registry key is the bare foundation-model ID (qwen.qwen3-vl-235b-a22b, "cross_region": false) and its application inference profile wraps the foundation model directly in the deploy Region, so cost attribution still works — but inference stays In-Region rather than routing across the US geography. It is available only where the model card lists In-Region support; us-west-2 is one such Region.
Two consequences:
- Requests can route to Regions you have not enabled. Per cross-Region inference general considerations, "Cross-Region inference can route requests to AWS Regions that are not manually enabled in your AWS account." Prompts and outputs may be stored in a destination Region for abuse detection. Data stays on the AWS network and is encrypted in transit.
- Nothing else moves. S3, DynamoDB, Cognito, Lambda, ECR, the AgentCore Runtime and the UI all live in your deployment Region. Only Bedrock inference crosses Regions.
In-Region inference would keep everything in one Region, and BADGERS does not use it because it is not available: all ten Converse models report In-Region as not-supported on the bedrock-runtime endpoint in every US Region. Geo (us.*) is the most Region-restrictive option the model set actually offers. Global (global.*) is the same mechanism over every commercial Region worldwide.
If you have hard data-residency requirements, this model set cannot meet them on bedrock-runtime.
Geo cross-Region inference requires bedrock:InvokeModel on the foundation model in the source Region and in every destination Region the profile can route to (IAM policy requirements). A foundation-model ARN has a mandatory Region field — arn:aws:bedrock:{region}::foundation-model/{model} — so granting "in every destination Region" means either enumerating those Regions or wildcarding the field.
iam_stack.py wildcards it: arn:aws:bedrock:*::foundation-model/{model}. The model ID stays pinned exactly, and no action or account is wildcarded. This trips AwsSolutions-IAM5, which is suppressed with the reasoning recorded inline. The short version:
- The destination set depends on both the model and the operator-chosen source Region, so it is not knowable when the code is written.
- Only 4 of the 10 Converse model cards publish a destination-Region table, so a hardcoded list would cover less than half the set. (Gemma 4 31B is mantle-only and has no
us.*profile, so it is not part of this reasoning.) bedrock:GetInferenceProfilereturns the Region-qualified foundation model ARNs inmodels[].modelArnfor each, but that is a deploy-time API call and would require a CDK custom resource.
Service Control Policies and geo cross-Region inference interact badly by default:
If any destination Region in a cross-Region inference profile is blocked in your SCPs, the request will fail even if other Regions remain allowed.
Allow Bedrock inference actions in all US destination Regions, or add an inference-profile exception. See SCP requirements for Geographic cross-Region inference.
BADGERS ships with 5 base specialists. Organizations can create additional specialists using the wizard UI without modifying the core deployment.
The wizard writes to the local working tree, not to S3. CustomSpecialistsStack reads
these paths at synth time, so the artifacts must exist on disk before a deploy:
deployment/custom_specialists/
├── specialist_registry.json # top-level key: "specialists"
├── manifests/{name}.json # 2nd top-level key: "specialist"
├── schemas/{name}.json # a single-element list
└── prompts/{name}/
├── {short}_gestalt.xml # the six generated prompt sections
├── {short}_job_role.xml
├── {short}_context.xml
├── {short}_rules.xml
├── {short}_tasks.xml
├── {short}_format.xml
└── few-shot-images/ # up to 6 example images, optional
Nothing writes code/ — the stack generates lambda_handler.py at synth.
-
Create the specialist via the 🧙 Create Specialist tab in the UI. The wizard generates the six prompts with Bedrock, then 💾 Save Specialist writes the tree above. Save is a distinct step from deploy, and ☁️ Deploy Stack stays disabled until a save succeeds.
-
Deploy, either from the wizard's Deploy Stack button or directly:
cd deployment ./deploy_custom_specialists.shThe script reads the local
custom_specialists/specialist_registry.json, exits cleanly if it is missing or lists no specialists, and runscdk deploy --exclusivelyon the CustomSpecialists stack.
Note
Creating specialist_registry.json is what makes the CustomSpecialists stack join
cdk deploy --all. Delete test artifacts when you are finished with them.
sync_custom_specialists.sh pulls specialists down from a deployed config bucket into
custom_specialists/. That is for adopting specialists created elsewhere — it is not a step
in the wizard flow, which never uploads to S3 in the first place.
The custom stack:
- Creates Lambda functions for each custom specialist
- Registers them as Gateway targets via Custom Resource
- Uses the same foundation layer and IAM role as base specialists
| Type | Editor Behavior |
|---|---|
| Base | Read-only by default, toggle to enable with warning |
| Custom | Always editable |
See the 🧙 Create Specialist tab in the UI for detailed usage.
Update specific components:
# Lambda code changes uv run cdk deploy BADGERS-Lambda-{id}-{suffix} --require-approval never # Gateway target changes uv run cdk deploy BADGERS-Gateway-{id}-{suffix} --require-approval never # Agent container changes cd runtime && ./build_and_push_websocket.sh && cd .. uv run cdk deploy BADGERS-RuntimeWebSocket-{id}-{suffix} --require-approval never # Prompt/manifest changes only ./sync_s3_files.sh
Gateway uses Cognito OAuth 2.0 client credentials:
- Credentials stored in Secrets Manager
- Runtime fetches tokens automatically
- Resource server scope:
agentcore-gateway/invoke
Gateway logs are automatically configured:
- 📝 Application:
/aws/vendedlogs/bedrock-agentcore/gateway/APPLICATION_LOGS/ - 📈 Usage:
/aws/vendedlogs/bedrock-agentcore/gateway/USAGE_LOGS/ - 🔍 Traces: X-Ray via CloudWatch Transaction Search
Warning
Manual step required: After deployment, enable Runtime observability in the AWS Console:
- Navigate to Amazon Bedrock → AgentCore → Runtimes
- Select your runtime and click "Edit"
- Enable Application logs and Usage logs
- Enable Tracing for X-Ray integration
- Runtime logs will appear at
/aws/bedrock-agentcore/runtimes/
Caution
This permanently deletes all resources including S3 buckets and their contents, and all job records in the DynamoDB jobs table.
From the repository root:
./destroy.sh
Like deploy.sh, it asks what to tear down — but it discovers deployments from
CloudFormation, not from .deploy-state/. A state file can be deleted while the stacks
are still live, so the stacks are the source of truth:
Scanning CloudFormation for BADGERS-*-{id}-{suffix} stacks...
Deployments found in us-west-2 — newest first:
1) dev suffix a1b 11 stack(s) created 2026-08-04T19:11:24Z
2) demo suffix c7f 14 stack(s) created 2026-08-02T10:02:11Z
Destroy which? (1-2, or q to abort):
You are then required to type the DEPLOYMENT_ID to confirm.
You can still pass it explicitly — DEPLOYMENT_ID=dev ./destroy.sh — in which case it is
validated against the naming rules and checked against what is actually deployed. If no
stacks match BADGERS-*-{id}-{suffix}, it refuses rather than running a teardown that
quietly does nothing.
- Empties the config, source and output buckets, including all versions and delete
markers. The buckets also have
auto_delete_objects, so this is belt and braces. - Deletes the ECS Express service, then polls until it is gone. This uses
delete-express-gateway-service—delete-servicerejects an Express Gateway Service outright with "has ResourceManagementType=ECS use DeleteExpressGatewayService". Deleting the Express service also removes the load balancer it created, provided no other service is sharing it. - Deletes the AgentCore runtime endpoints, then the runtime, and waits. These calls go
to
bedrock-agentcore-control; thebedrock-agentcoreservice only exposesInvokeAgentRuntime, so aiming control-plane calls at it fails silently. - Sweeps ENIs in the VPC. CloudFormation cannot delete a VPC while an ENI is still attached, and both the ECS service and the runtime release theirs asynchronously, well after they report gone.
- Destroys all 14 stacks in reverse dependency order — see the table below. ECS goes before VPC because it imports three VPC exports.
- Verifies every stack is gone. If the VPC stack is
DELETE_FAILED, it retries with--retain-resources, sweeps ENIs again, then re-verifies. - Schedules the KMS key for deletion, but only once the stacks are confirmed gone.
Scheduling it after a failed teardown would mark a live deployment's in-use key for
deletion, which is unrecoverable once the window expires. The default 7-day window is
deliberate: the alias
alias/badgers-s3-key-{id}-{suffix}stays reserved until the key is gone, so a long window blocks redeploying under the sameDEPLOYMENT_ID. Override withKMS_WAIT_DAYS(7–30).
A teardown that leaves stacks standing exits non-zero and prints
❌ Teardown incomplete with the survivors listed. It does not print a success banner over
a failed run, and it does not schedule the KMS key — it tells you the key was left alone
and gives you the ARN.
Re-run it once the cause is fixed; it is safe to run repeatedly. Scroll up to the first
error: a cdk synth or destroy failure aborts before any stack is touched, so everything
after it is a consequence rather than the cause.
To sweep ENIs from a VPC left behind by an earlier failed teardown:
DEPLOYMENT_ID=dev STACK_SUFFIX=a1b ./destroy.sh --vpc-cleanup-only
That flag needs both values explicitly, since it skips the discovery step.
- CloudWatch Logs resource policies created by vended log delivery. Nothing deletes an
AWSLogDeliveryWrite*policy when its delivery source disappears, so they accumulate against the non-adjustable quota of 10 per region across repeated deploy/destroy cycles. See X-Ray and the CloudWatch Logs resource policy quota. - The KMS key itself until its pending-deletion window expires. Cancel with
aws kms cancel-key-deletion --key-id <arn>if you scheduled it by mistake. .deploy-state/{DEPLOYMENT_ID}.json. Delete it yourself once the stacks are gone, or the deploy menu will keep offering a deployment that no longer exists.- CloudWatch log groups with a retention policy still counting down.
Use this when destroy.sh cannot run — no local environment, a partially renamed stack set
that discovery does not match, or a teardown wedged badly enough that you want to drive it
by hand.
Important
Two things must happen before you delete any stack. Neither is a CloudFormation resource, and skipping either will wedge a stack delete.
The ECS console can do this, or:
aws ecs delete-express-gateway-service --region us-west-2 \ --service-arn arn:aws:ecs:us-west-2:<account>:service/default/badgers-ui-{id}-{suffix}
DeleteService will not work on it. Its ENIs block the VPC stack later, and deleting it
also removes the load balancer it created.
Bedrock AgentCore console → delete the runtime's endpoints first, then the runtime. Or:
aws bedrock-agentcore-control list-agent-runtimes --region us-west-2 aws bedrock-agentcore-control list-agent-runtime-endpoints --region us-west-2 --agent-runtime-id <id> aws bedrock-agentcore-control delete-agent-runtime-endpoint --region us-west-2 \ --agent-runtime-id <id> --endpoint-name <name> aws bedrock-agentcore-control delete-agent-runtime --region us-west-2 --agent-runtime-id <id>
Note the service name: bedrock-agentcore-control, not bedrock-agentcore.
CloudFormation → select the stack → Delete. Wait for DELETE_COMPLETE before starting
the next one.
| # | Stack | Notes |
|---|---|---|
| 1 | BADGERS-CustomSpecialists-{id}-{suffix} |
Only exists if you created custom specialists |
| 2 | BADGERS-ECS-{id}-{suffix} |
Step 1 above must be done first |
| 3 | BADGERS-RuntimeWebSocket-{id}-{suffix} |
Step 2 above must be done first |
| 4 | BADGERS-Gateway-{id}-{suffix} |
|
| 5 | BADGERS-Lambda-{id}-{suffix} |
|
| 6 | BADGERS-Memory-{id}-{suffix} |
|
| 7 | BADGERS-XRay-{id}-{suffix} |
Often absent — skipped when Transaction Search was already on |
| 8 | BADGERS-ECR-{id}-{suffix} |
Images are removed automatically (empty_on_delete) |
| 9 | BADGERS-InferenceProfiles-{id}-{suffix} |
|
| 10 | BADGERS-IAM-{id}-{suffix} |
|
| 11 | BADGERS-DynamoDB-{id}-{suffix} |
Deletes the jobs table and all job records |
| 12 | BADGERS-S3-{id}-{suffix} |
Buckets empty themselves (auto_delete_objects) |
| 13 | BADGERS-Cognito-{id}-{suffix} |
Deletes the user pool and all users |
| 14 | BADGERS-Vpc-{id}-{suffix} |
Always last. Most likely to fail — see below |
Do not delete them in parallel. Several export values that later stacks import, and
CloudFormation refuses to delete a stack whose exports are still in use — a parallel delete
fails with Export ... cannot be deleted as it is in use.
Not every stack will exist. Skip what is not there.
DELETE_FAILED on the VPC is almost always a leftover ENI from the ECS service or the
AgentCore runtime. Find them in the EC2 console under Network Interfaces, filtered by
VPC, or:
aws ec2 describe-network-interfaces --region us-west-2 \ --filters "Name=vpc-id,Values=<vpc-id>" \ --query "NetworkInterfaces[].[NetworkInterfaceId,Status,Description]" --output table
Detach then delete any that remain, and retry the stack delete. An ENI in available
status can be deleted directly; one that is in-use still has an owner, which means step 1
or step 2 did not complete.
If CloudFormation still refuses, delete the stack again and choose retain for the failed resources, then remove those resources by hand afterwards.
- KMS key — KMS console → the key behind
alias/badgers-s3-key-{id}-{suffix}→ Schedule key deletion. Nothing schedules it for you when tearing down by hand, and the alias stays reserved until it is gone. - CloudWatch Logs resource policies — check for
AWSLogDeliveryWrite*policies left behind by vended log delivery. These are invisible in the IAM console; they live under CloudWatch Logs and are only reachable viaaws logs describe-resource-policies. .deploy-state/{DEPLOYMENT_ID}.json— delete it so the deploy menu stops offering a deployment that no longer exists.
cd lambdas # Foundation layer rm -rf layer/ layer.zip ./build_foundation_layer.sh # Poppler layer rm -rf poppler_build/ poppler-qpdf-layer.zip ./build_poppler_qdf_layer.sh # Enhancement layer — no longer deployed, runs in container Lambda # rm -rf enhancement_build/ enhancement-layer.zip # ./build_enhancement_layer.sh
# Verify image exists aws ecr describe-images --repository-name pdf-analysis-agent-<deployment_id> # Rebuild cd runtime && ./build_and_push_websocket.sh
# Check credentials aws secretsmanager get-secret-value \ --secret-id pdf-extractor/cognito-config-<deployment_id>
# Tail logs aws logs tail /aws/bedrock-agentcore/runtimes/<runtime_id> --follow
deploy.sh keeps this consistent for you: the suffix is generated once per
DEPLOYMENT_ID and reused on every subsequent run, so redeploying targets the same stacks.
./deploy.sh # pick the deployment, then option 10 for suffix and step status cat .deploy-state/dev.json # or read it directly
To drive cdk yourself, supply both values — see
Stack and Resource Naming.
DEPLOYMENT_ID=dev STACK_SUFFIX=a1b uv run cdk deploy --all
Deleting
.deploy-state/{DEPLOYMENT_ID}.jsonloses the suffix. A laterdeploy.shrun would generate a new one and deploy a second, parallel set of stacks rather than updating the existing ones.Recovering it is straightforward, because stack names contain both values. List what is deployed and read the id and suffix off any stack name:
aws cloudformation list-stacks --region us-west-2 \ --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE \ --query "StackSummaries[?starts_with(StackName,'BADGERS-')].StackName" --output text
BADGERS-S3-dev-a1bmeansDEPLOYMENT_ID=dev,STACK_SUFFIX=a1b. Recreate the file with at least those two keys — every step flag being absent simply reads as incomplete, and all steps are idempotent:printf '{\n "deployment_id": "dev",\n "stack_suffix": "a1b"\n}\n' > .deploy-state/dev.json
./destroy.shdoes not need the state file at all — it discovers deployments from CloudFormation.
All resources are tagged using a centralized configuration in app.py. Customize the deployment_tags dict before deployment:
deployment_tags = { "application_name": "badgers", "application_description": "BADGERS (Broad Agentic Document Generative Extraction & Recognition System)", "environment": "dev", "owner": "your-team", "cost_center": "your-cost-center", "project_code": "your-project-code", "cdk_stack_prefix": STACK_PREFIX, "team": "your-team", "team_contact_email": "[email protected]", }
These tags are applied to all resources across all stacks. Additionally, each resource gets:
resource_name- Identifier for the specific resourceresource_description- Description of the resource's purpose
Tagged resources include:
- AgentCore Gateway, Runtime, Memory
- ECR repositories
- S3 buckets and KMS keys
- Lambda functions and layers
- Cognito User Pool, Identity Pool, Secrets
- IAM roles
