From 3cc04a5047ada8d73f41691a477de41e30b9684c Mon Sep 17 00:00:00 2001 From: achand_microsoft <115764250+achand_microsoft@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:27:01 -0700 Subject: [PATCH] fix: require and persist Anthropic industry attestation Collect Industry during preup before azd resolves required inputs, preserve legacy environments, and keep Bicep and Terraform validation in parity. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .env.sample | 5 +- .github/agents/claude-on-foundry.agent.md | 2 +- .github/copilot-instructions.md | 6 +- AGENTS.md | 5 +- README.md | 33 ++++- infra-bicep/azure.yaml | 16 ++ infra-bicep/infra/foundry.bicep | 12 ++ infra-bicep/infra/main.bicep | 4 +- infra-bicep/infra/main.parameters.json | 2 +- infra-terraform/azure.yaml | 16 ++ infra-terraform/infra/main.tfvars.json | 2 +- infra-terraform/infra/variables.tf | 5 +- scripts/preflight-claude.ps1 | 65 ++++++++- scripts/preflight-claude.sh | 56 ++++++- skills/claude-on-foundry/SKILL.md | 11 +- tests/test_catalog.py | 169 ++++++++++++++++++++-- tests/test_industry_templates.py | 80 ++++++++++ 17 files changed, 447 insertions(+), 42 deletions(-) create mode 100644 tests/test_industry_templates.py diff --git a/.env.sample b/.env.sample index d881148..45a2f01 100644 --- a/.env.sample +++ b/.env.sample @@ -1,9 +1,10 @@ # --- Required --------------------------------------------------------------- # Surfaced via modelProviderData on the Claude deployment. -# `industry` MUST be lowercase to match the Foundry portal dropdown. +# Industry is required: choose the lowercase value matching your organization. CLAUDE_ORGANIZATION_NAME=Your Organization CLAUDE_COUNTRY_CODE=US -CLAUDE_INDUSTRY=technology +# INDUSTRY=technology +# Legacy CLAUDE_INDUSTRY values are migrated automatically by the azd hook. # --- Optional --------------------------------------------------------------- AZURE_LOCATION=eastus2 diff --git a/.github/agents/claude-on-foundry.agent.md b/.github/agents/claude-on-foundry.agent.md index 057d4a3..b819691 100644 --- a/.github/agents/claude-on-foundry.agent.md +++ b/.github/agents/claude-on-foundry.agent.md @@ -38,7 +38,7 @@ Translate plain-English requests ("deploy", "it failed", "is it working", "add a ### 2. Configure (only what's needed) 1. Set config via `azd env set ` from inside the chosen variant folder (`infra-bicep/` or `infra-terraform/`). -2. Required: `CLAUDE_ORGANIZATION_NAME`, `AZURE_LOCATION`. Industry must be lowercase. +2. Required: `CLAUDE_ORGANIZATION_NAME`, `AZURE_LOCATION`, `INDUSTRY`. Industry has no default: `preup` prompts once from the documented lowercase list and saves it before azd resolves template inputs; legacy `CLAUDE_INDUSTRY` values migrate automatically. 3. Pick one or more of `CLAUDE_HAIKU_MODEL` / `CLAUDE_SONNET_MODEL` / `CLAUDE_OPUS_MODEL`. Empty = skip. ### 3. Execute diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 00bfa73..fcaf065 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -9,7 +9,8 @@ This is the **Claude on Foundry Starter Kit** ([`Azure-Samples/claude`](https:// - **Two IaC variants ship side-by-side. The user picks ONE.** Never edit or run both. - Bicep: [`infra-bicep/`](../infra-bicep) — run `cd infra-bicep && azd up` - Terraform: [`infra-terraform/`](../infra-terraform) — run `cd infra-terraform && azd up` -- **Two hooks fire automatically during `azd up`** (defined in each variant's `azure.yaml`): +- **Three hooks fire automatically during `azd up`** (defined in each variant's `azure.yaml`): + - `preup` → the preflight script's Industry-only mode collects and saves `INDUSTRY` before azd resolves required template inputs. - `preprovision` → [`scripts/preflight-claude.ps1`](../scripts/preflight-claude.ps1) / `.sh` — marketplace catalog + quota check, hard-fails early on missing offers or insufficient TPM. - `postprovision` → [`scripts/configure-claude-code.ps1`](../scripts/configure-claude-code.ps1) / `.sh` — writes activator files + `.vscode/settings.json` + `.claude/settings.json` so Claude Code and the SDK target the new Foundry deployment via Entra ID. - **One canonical catalog tool:** [`./Get-ClaudeCatalog.ps1`](../Get-ClaudeCatalog.ps1). Zero-required-params. Run with `-Latest` for the newest generation per family. @@ -21,7 +22,8 @@ This is the **Claude on Foundry Starter Kit** ([`Azure-Samples/claude`](https:// |---|---|---|---| | `CLAUDE_ORGANIZATION_NAME` | yes | — | Anthropic attestation (legal entity) | | `CLAUDE_COUNTRY_CODE` | attest | `US` | Anthropic attestation (ISO-2) | -| `CLAUDE_INDUSTRY` | attest | `technology` | Anthropic attestation (**lowercase only**) | +| `INDUSTRY` | attest (yes) | — | Required Anthropic attestation; `preup` prompts once from the documented lowercase list and saves it before template input resolution | +| `CLAUDE_INDUSTRY` | legacy alias | — | Migrated to `INDUSTRY` without prompting; explicit `INDUSTRY` takes precedence | | `AZURE_LOCATION` | yes | — | `eastus2` / `swedencentral` / `westus2` (opus+sonnet only) | | `CLAUDE_HAIKU_MODEL` | no | empty | e.g. `claude-haiku-5-5`. Empty = skip family. | | `CLAUDE_SONNET_MODEL` | no | empty | e.g. `claude-sonnet-5-5`. Empty = skip family. | diff --git a/AGENTS.md b/AGENTS.md index 48f5f20..d903c52 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,11 +17,12 @@ The always-on rules below are the same ones in [`.github/copilot-instructions.md - **Two IaC variants ship side by side. The user picks ONE.** Never edit or run both in the same `azd env`. - Bicep: [`infra-bicep/`](./infra-bicep/) — run `cd infra-bicep && azd up` - Terraform: [`infra-terraform/`](./infra-terraform/) — run `cd infra-terraform && azd up` -- **Single entrypoint:** `azd up` from inside the chosen variant folder. Two hooks fire automatically: +- **Single entrypoint:** `azd up` from inside the chosen variant folder. Three hooks fire automatically: + - `preup` collects and saves `INDUSTRY` before azd resolves required template inputs. - `preprovision` runs [`scripts/preflight-claude.ps1`](./scripts/preflight-claude.ps1) (catalog + quota gate). Never bypass it. - `postprovision` runs [`scripts/configure-claude-code.ps1`](./scripts/configure-claude-code.ps1) to wire Claude Code + the SDK to the new deployment. - **Configure via `azd env set `** from inside the chosen variant folder. There is no `.env` file. See the env-var contract in [`.github/copilot-instructions.md`](.github/copilot-instructions.md). -- **`CLAUDE_INDUSTRY` must be lowercase**: `technology`, `finance`, `healthcare`, `education`, `retail`, `manufacturing`, `government`, `media`, `other`. Uppercase fails with `AnthropicOrganizationCreationException`. +- **`INDUSTRY` is required with no default**: `technology`, `finance`, `healthcare`, `education`, `retail`, `manufacturing`, `government`, `media`, `other` (lowercase, per the [official guide](https://learn.microsoft.com/azure/developer/ai/how-to/deploy-claude-foundry#configure-required-deployment-values)). The `preup` hook prompts once and saves it; existing `CLAUDE_INDUSTRY` values migrate without prompting. - **Honor the user's region.** `eastus2` and `swedencentral` host all three families; `westus2` is sonnet + opus only. Don't silently change `AZURE_LOCATION`. - **Passwordless only.** Microsoft Entra ID via `DefaultAzureCredential` / `az login`. Never write `CLAUDE_API_KEY`, subscription IDs, tenant IDs, or tokens into any tracked file. Real values live in env vars, the gitignored `.env.local`, or the gitignored `.azure-cli/` token cache. - **Confirm before destructive actions.** Always get explicit user OK before: `azd down`, `az cognitiveservices account purge`, `az role assignment delete`, deleting `.azure-cli/`, editing `~/.claude/settings.json`. Never pass `--no-prompt` to skip hooks. diff --git a/README.md b/README.md index fc7ec06..123188b 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Current examples use **Claude Sonnet 5.5, Haiku 5.5, and Opus 5.5**. Verify mode ![Architecture: azd up provisions a Foundry account, project, and Claude deployments; the postprovision hook configures the local workspace so the Python SDK and Claude Code CLI both call the deployment via Entra ID.](./docs/img/architecture.png) > [!IMPORTANT] -> By running `azd up` you accept Anthropic's commercial terms for Claude. Three short attestation fields (`CLAUDE_ORGANIZATION_NAME`, `CLAUDE_COUNTRY_CODE`, `CLAUDE_INDUSTRY`) are sent to Anthropic with every request and must match your real organization. **[Read the Terms of use](#terms-of-use) before you deploy.** +> By running `azd up` you accept Anthropic's commercial terms for Claude. Three short attestation fields (`CLAUDE_ORGANIZATION_NAME`, `CLAUDE_COUNTRY_CODE`, `INDUSTRY`) accompany each model deployment and must match your real organization. **[Read the Terms of use](#terms-of-use) before you deploy.**
Important — please read: Terms of use @@ -46,9 +46,9 @@ The Terraform and Bicep in this template both send a `modelProviderData` block ( 2. **Update the three attestation fields so they accurately describe your organization** — see the highlighted rows in [All configuration variables](#all-configuration-variables): - `CLAUDE_ORGANIZATION_NAME` (no default — required) - `CLAUDE_COUNTRY_CODE` (default `US`) - - `CLAUDE_INDUSTRY` (default `technology`) + - `INDUSTRY` (required; no default) - These values are sent to Anthropic on every request and are part of your acceptance — they should match the real legal entity, country of operation, and industry that will use the model. + These values accompany each deployment as part of your acceptance — they should match the real legal entity, country of operation, and industry that will use the model. 3. Confirm your Azure subscription is [eligible to deploy Anthropic models in Foundry](https://learn.microsoft.com/azure/ai-foundry/foundry-models/how-to/use-foundry-models-claude#prerequisites).
@@ -101,7 +101,9 @@ azd env set CLAUDE_SONNET_MODEL "claude-sonnet-5-5" azd up ``` -That's it. To deploy other families, tweak capacity, or change attestation, see [Choosing which models to deploy](#choosing-which-models-to-deploy) and [All configuration variables](#all-configuration-variables) in Advanced. +The `preup` hook prompts for your Industry once and saves it before `azd up` resolves required template inputs. To preconfigure it (including in CI or before standalone `azd provision`), run `azd env set INDUSTRY technology`, replacing the example with your organization's actual industry. Existing `CLAUDE_INDUSTRY` settings are migrated without another prompt. + +To deploy other families, tweak capacity, or change attestation, see [Choosing which models to deploy](#choosing-which-models-to-deploy) and [All configuration variables](#all-configuration-variables) in Advanced.
Zero-touch in GitHub Codespaces — no local install, runs in your browser @@ -147,7 +149,7 @@ This repo ships an open [Agent Skills](https://agentskills.io/) playbook. Any as That's the full one-shot — just swap the bolded values to suit you. Optional additions: - *"…also deploy **haiku** and **opus**"* — multi-family deployment in one shot. -- *"…country **GB**, industry **finance**"* — if your org isn't US tech (defaults are `US` / `technology`). +- *"…country **GB**, industry **finance**"* — country defaults to `US`; Industry must be selected explicitly. - *"…with **`ASSIGN_RBAC=true`**"* — also grant yourself the least-privilege inference role. - *"…install Claude Code automatically"* — sets `CLAUDE_CODE_AUTO_INSTALL=true`. @@ -326,7 +328,8 @@ Rows marked **Attest** below are the three `modelProviderData` fields sent to An |---|---|---|---| | `CLAUDE_ORGANIZATION_NAME` | **Attest** (yes) | — | **Legal entity name** sent to Anthropic via `modelProviderData`. | | `CLAUDE_COUNTRY_CODE` | **Attest** | `US` | 2-letter ISO. Country your organization operates from. | -| `CLAUDE_INDUSTRY` | **Attest** | `technology` | **lowercase**: `technology`, `finance`, `healthcare`, `education`, `retail`, `manufacturing`, `government`, `media`, `other` | +| `INDUSTRY` | **Attest** (yes) | — | Prompted once and saved by `preup`, then validated again by `preprovision`. Must match a documented lowercase Industry value. | +| `CLAUDE_INDUSTRY` | legacy alias | — | Existing values are migrated to `INDUSTRY` without prompting. An explicit `INDUSTRY` takes precedence. | | `AZURE_LOCATION` | yes | — | `eastus2` / `swedencentral` (all 3 families) / `westus2` (sonnet + opus) | | `CLAUDE_HAIKU_MODEL` | no | *(empty)* | Haiku family model id (e.g. `claude-haiku-5-5`). Empty = skip. | | `CLAUDE_SONNET_MODEL` | no | *(empty)* | Sonnet family model id (e.g. `claude-sonnet-5-5`). Empty = skip. | @@ -342,6 +345,17 @@ Rows marked **Attest** below are the three `modelProviderData` fields sent to An | `CLAUDE_CODE_AUTO_INSTALL` | no | `false` | `true` to let the postprovision hook run the official Claude Code installer ([`install.ps1`](https://claude.ai/install.ps1) / [`install.sh`](https://claude.ai/install.sh)) when `claude` isn't already on PATH | | `CLAUDE_WRITE_VSCODE_SETTINGS` | no | `false` | `true` to opt in to having the postprovision hook write `.vscode/settings.json` for the [Claude Code VS Code extension](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code). Default skips it — the CLI / SDK don't need workspace settings. | +**Industry attestation.** Anthropic requires your organization's Industry alongside its legal name and country for model-provider onboarding. Both IaC variants send it as **`properties.modelProviderData.industry`**, next to `organizationName` and `countryCode`; it is not a tag or an SDK authentication setting. + +The [official deployment guide](https://learn.microsoft.com/azure/developer/ai/how-to/deploy-claude-foundry#configure-required-deployment-values) publishes these lowercase values: `technology`, `finance`, `healthcare`, `education`, `retail`, `manufacturing`, `government`, `media`, `other`. The `preup` hook presents the same list as a numbered menu and accepts a number or exact value: + +```powershell +azd env set INDUSTRY finance # example only; choose your organization's actual industry +azd up +``` + +Run these commands from your chosen variant folder. A configured value skips the menu, so CI can remain non-interactive; a missing or invalid value fails with a configuration message rather than silently attesting `technology`. There is no assumed service default (including `NONE`). Existing environments with `CLAUDE_INDUSTRY` keep their choice; only the canonical env key is added. No portal action is required. +
@@ -575,6 +589,7 @@ What the preflight does, and does not, do: | Check | Behavior | |---|---| +| `INDUSTRY` | Required. `preup` collects and saves the documented choice before template input resolution; `preprovision` revalidates it. Existing legacy values are migrated; invalid values or a missing value in CI fail with exit 1. | | `CLAUDE_ORGANIZATION_NAME` / `AZURE_LOCATION` set | Warns if missing; skips region-dependent checks when no location is set so azd can prompt. Missing Azure CLI/login also produces a warning. | | Claude 5.5 model and public Marketplace offer | Checks the regional model catalog and the public `claude--5-5-offer` listing without sending Azure credentials. Missing models/offers hard-fail with exit 4. The `-fast` variant has no standalone offer; its regional catalog entry is checked and the RP validates applicable terms. | | Legacy Marketplace offer/plan resolves | Hard fail (exit 4) on "offer not found", using legacy `anthropic--offer` / `anthropic--plan-new` IDs. | @@ -682,7 +697,9 @@ az cognitiveservices usage list -l --query "[?contains(name.value,'clau
Why modelProviderData matters -Claude deployments fail with `AnthropicOrganizationCreationException` if `modelProviderData` is missing. **`industry` must be lowercase** to match the Foundry portal dropdown. +Claude deployments fail with `AnthropicOrganizationCreationException` if `modelProviderData` is missing. **`industry` must be a documented lowercase value**. Both variants require it without a default and pass it alongside `organizationName` and `countryCode`. + +The public [2025-10-01-preview ARM reference](https://learn.microsoft.com/azure/templates/microsoft.cognitiveservices/2025-10-01-preview/accounts/deployments) does not currently list `modelProviderData`; the field names are documented in the [Microsoft Learn starter sample](https://learn.microsoft.com/samples/azure-samples/claude/claude/) and retained unchanged here. The published Industry list comes from the deployment guide linked above, not an ARM-schema enum. The Terraform variant uses `azapi_resource` for both the Foundry account and the Claude deployment, because the native `azurerm_cognitive_account` / `azurerm_cognitive_deployment` resources do not yet expose `allowProjectManagement` or `modelProviderData` ([tracked here](https://github.com/hashicorp/terraform-provider-azurerm/issues/31140)). The Bicep variant uses native resources at API version `2025-10-01-preview`, which support both. @@ -693,7 +710,7 @@ The Terraform variant uses `azapi_resource` for both the Foundry account and the | Symptom | Fix | |---|---| -| `AnthropicOrganizationCreationException` / `AnthropicOrganizationCreationFailed` | `modelProviderData` is missing or malformed. Ensure all three of `organizationName`, `countryCode`, `industry` are set, and that `industry` is lowercase. | +| `AnthropicOrganizationCreationException` / `AnthropicOrganizationCreationFailed` | `modelProviderData` is missing or malformed. Ensure `organizationName`, `countryCode`, and `industry` are present. Set a documented lowercase Industry with `azd env set INDUSTRY ` in the chosen variant folder. | | `Project can only be created under AIServices Kind account with allowProjectManagement set to true` | Account property missing. Both variants here set it; check you didn't downgrade the API version. | | `404 Not Found` on inference | Base URL must end in `/anthropic` — `https://.services.ai.azure.com/anthropic`. | | `401 Unauthorized` | Token scope must be `https://ai.azure.com/.default`. Re-run `az login`. | diff --git a/infra-bicep/azure.yaml b/infra-bicep/azure.yaml index d128fc5..8b9e228 100644 --- a/infra-bicep/azure.yaml +++ b/infra-bicep/azure.yaml @@ -7,12 +7,28 @@ infra: path: infra module: main hooks: + preup: + windows: + shell: pwsh + interactive: true + run: pwsh -NoProfile -ExecutionPolicy Bypass -File ../scripts/preflight-claude.ps1 -IndustryOnly + posix: + shell: sh + interactive: true + run: | + if command -v pwsh >/dev/null 2>&1; then + pwsh -NoProfile -File ../scripts/preflight-claude.ps1 -IndustryOnly + else + bash ../scripts/preflight-claude.sh --industry-only + fi preprovision: windows: shell: pwsh + interactive: true run: pwsh -NoProfile -ExecutionPolicy Bypass -File ../scripts/preflight-claude.ps1 posix: shell: sh + interactive: true run: | if command -v pwsh >/dev/null 2>&1; then pwsh -NoProfile -File ../scripts/preflight-claude.ps1 diff --git a/infra-bicep/infra/foundry.bicep b/infra-bicep/infra/foundry.bicep index 3a8a454..d42c1c9 100644 --- a/infra-bicep/infra/foundry.bicep +++ b/infra-bicep/infra/foundry.bicep @@ -19,6 +19,18 @@ param modelVersion string param claudeOrganizationName string param claudeCountryCode string +@description('Required Anthropic industry attestation. Use a lowercase value from the documented Foundry industry list.') +@allowed([ + 'technology' + 'finance' + 'healthcare' + 'education' + 'retail' + 'manufacturing' + 'government' + 'media' + 'other' +]) param claudeIndustry string param principalId string param assignRbac string diff --git a/infra-bicep/infra/main.bicep b/infra-bicep/infra/main.bicep index 53e370c..f214d11 100644 --- a/infra-bicep/infra/main.bicep +++ b/infra-bicep/infra/main.bicep @@ -72,7 +72,7 @@ param claudeOrganizationName string @minLength(2) @maxLength(2) param claudeCountryCode string = 'US' -@description('Industry — MUST be lowercase to match Foundry portal dropdown.') +@description('Required Anthropic industry attestation (INDUSTRY). Supported lowercase values: https://learn.microsoft.com/azure/developer/ai/how-to/deploy-claude-foundry#configure-required-deployment-values') @allowed([ 'technology' 'finance' @@ -84,7 +84,7 @@ param claudeCountryCode string = 'US' 'media' 'other' ]) -param claudeIndustry string = 'technology' +param claudeIndustry string var tags = { 'azd-env-name': environmentName diff --git a/infra-bicep/infra/main.parameters.json b/infra-bicep/infra/main.parameters.json index 54e6b7c..d9ac0c6 100644 --- a/infra-bicep/infra/main.parameters.json +++ b/infra-bicep/infra/main.parameters.json @@ -18,6 +18,6 @@ "modelCapacity": { "value": "${CLAUDE_MODEL_CAPACITY=25}" }, "claudeOrganizationName": { "value": "${CLAUDE_ORGANIZATION_NAME}" }, "claudeCountryCode": { "value": "${CLAUDE_COUNTRY_CODE=US}" }, - "claudeIndustry": { "value": "${CLAUDE_INDUSTRY=technology}" } + "claudeIndustry": { "value": "${INDUSTRY}" } } } diff --git a/infra-terraform/azure.yaml b/infra-terraform/azure.yaml index 5e5cafc..a7af3bc 100644 --- a/infra-terraform/azure.yaml +++ b/infra-terraform/azure.yaml @@ -7,12 +7,28 @@ infra: path: infra module: main hooks: + preup: + windows: + shell: pwsh + interactive: true + run: pwsh -NoProfile -ExecutionPolicy Bypass -File ../scripts/preflight-claude.ps1 -IndustryOnly + posix: + shell: sh + interactive: true + run: | + if command -v pwsh >/dev/null 2>&1; then + pwsh -NoProfile -File ../scripts/preflight-claude.ps1 -IndustryOnly + else + bash ../scripts/preflight-claude.sh --industry-only + fi preprovision: windows: shell: pwsh + interactive: true run: pwsh -NoProfile -ExecutionPolicy Bypass -File ../scripts/preflight-claude.ps1 posix: shell: sh + interactive: true run: | if command -v pwsh >/dev/null 2>&1; then pwsh -NoProfile -File ../scripts/preflight-claude.ps1 diff --git a/infra-terraform/infra/main.tfvars.json b/infra-terraform/infra/main.tfvars.json index cb1d140..7d89520 100644 --- a/infra-terraform/infra/main.tfvars.json +++ b/infra-terraform/infra/main.tfvars.json @@ -16,5 +16,5 @@ "model_capacity": "${CLAUDE_MODEL_CAPACITY=25}", "claude_organization_name": "${CLAUDE_ORGANIZATION_NAME}", "claude_country_code": "${CLAUDE_COUNTRY_CODE=US}", - "claude_industry": "${CLAUDE_INDUSTRY=technology}" + "claude_industry": "${INDUSTRY}" } diff --git a/infra-terraform/infra/variables.tf b/infra-terraform/infra/variables.tf index e5dd11e..b669905 100644 --- a/infra-terraform/infra/variables.tf +++ b/infra-terraform/infra/variables.tf @@ -121,14 +121,13 @@ variable "claude_country_code" { } variable "claude_industry" { - description = "Industry — MUST be lowercase to match Foundry portal dropdown." + description = "Required Anthropic industry attestation (INDUSTRY). Supported lowercase values: https://learn.microsoft.com/azure/developer/ai/how-to/deploy-claude-foundry#configure-required-deployment-values" type = string - default = "technology" validation { condition = contains([ "technology", "finance", "healthcare", "education", "retail", "manufacturing", "government", "media", "other", ], var.claude_industry) - error_message = "industry must be a lowercase value supported by the Foundry portal." + error_message = "INDUSTRY must be technology, finance, healthcare, education, retail, manufacturing, government, media, or other (lowercase)." } } diff --git a/scripts/preflight-claude.ps1 b/scripts/preflight-claude.ps1 index 2ebae3c..8a5d00a 100644 --- a/scripts/preflight-claude.ps1 +++ b/scripts/preflight-claude.ps1 @@ -23,13 +23,15 @@ falls back to CLAUDE_MODEL_NAME (legacy single-model behavior). Env vars consumed: - CLAUDE_ORGANIZATION_NAME, AZURE_LOCATION, CLAUDE_HAIKU_MODEL, + INDUSTRY (or legacy CLAUDE_INDUSTRY), CLAUDE_ORGANIZATION_NAME, + AZURE_LOCATION, CLAUDE_HAIKU_MODEL, CLAUDE_SONNET_MODEL, CLAUDE_OPUS_MODEL (+ matching *_CAPACITY), CLAUDE_MODEL_NAME, CLAUDE_MODEL_CAPACITY (legacy fallback). .NOTES Exit codes: 0 Preflight passed (or skipped — see warnings). + 1 Missing/invalid Industry, canceled prompt, or azd env save failed. 4 Model or Marketplace offer not found (typo in a model name, or model not in the Anthropic-on-Foundry catalog yet). 6 Insufficient quota (Terraform variant only; on Bicep this is a @@ -48,7 +50,9 @@ #> [CmdletBinding()] -param() +param( + [switch] $IndustryOnly +) $ErrorActionPreference = "Stop" @@ -80,7 +84,62 @@ if (Test-Path $azureYaml) { elseif ($yaml -match '(?m)^\s*provider:\s*terraform') { $variant = 'terraform' } } -# --- 1. Required env vars --------------------------------------------------- +# --- 1. Required Industry attestation -------------------------------------- +# Published values: https://learn.microsoft.com/azure/developer/ai/how-to/deploy-claude-foundry#configure-required-deployment-values +$industries = @( + 'technology', 'finance', 'healthcare', 'education', 'retail', + 'manufacturing', 'government', 'media', 'other' +) +$industry = $env:INDUSTRY +$saveIndustry = $false +if ([string]::IsNullOrWhiteSpace($industry)) { + $industry = $env:CLAUDE_INDUSTRY + $saveIndustry = $true +} +if ([string]::IsNullOrWhiteSpace($industry)) { + if ($env:CI -and $env:CI -notmatch '^(0|false)$') { + Fail 1 "INDUSTRY is required. Set it before CI runs: azd env set INDUSTRY . Valid values: $($industries -join ', ')." + } + Write-Host "Anthropic requires your organization's Industry (no default):" + for ($i = 0; $i -lt $industries.Count; $i++) { + Write-Host (" {0}. {1}" -f ($i + 1), $industries[$i]) + } + try { + $choice = Read-Host 'Select an Industry number or enter its lowercase value' + } catch [System.Management.Automation.PSInvalidOperationException] { + Fail 1 "Cannot prompt for INDUSTRY in this shell. Set it first: azd env set INDUSTRY ." + } + if ([string]::IsNullOrWhiteSpace($choice)) { + Fail 1 "Industry selection canceled. Set it first: azd env set INDUSTRY ." + } + $choice = $choice.Trim() + if ($choice -match '^[1-9]$') { + $industry = $industries[[int]$choice - 1] + } else { + $industry = $choice + } +} +if ($industries -cnotcontains $industry) { + Fail 1 "Invalid INDUSTRY '$industry'. Choose one of: $($industries -join ', ') (lowercase)." +} +if ($saveIndustry) { + if (-not (Get-Command azd -ErrorAction SilentlyContinue)) { + Fail 1 "Cannot save INDUSTRY: azd is not on PATH. Install azd and rerun from the selected variant folder." + } + & azd env set INDUSTRY $industry + if ($LASTEXITCODE -ne 0) { + Fail 1 "Could not save INDUSTRY to the selected azd environment." + } +} +$env:INDUSTRY = $industry +if ($env:CLAUDE_INDUSTRY -and $env:CLAUDE_INDUSTRY -cne $industry) { + Warn "INDUSTRY overrides legacy CLAUDE_INDUSTRY. Update or remove the legacy value to avoid ambiguity." +} +if ($IndustryOnly) { + exit 0 +} + +# --- Other required env vars ----------------------------------------------- if (-not $env:CLAUDE_ORGANIZATION_NAME) { Warn "CLAUDE_ORGANIZATION_NAME is not set. azd will prompt for the 'claudeOrganizationName' Bicep parameter at provision time. To skip the prompt: azd env set CLAUDE_ORGANIZATION_NAME 'Your Org'" } diff --git a/scripts/preflight-claude.sh b/scripts/preflight-claude.sh index e3960a4..ebef535 100644 --- a/scripts/preflight-claude.sh +++ b/scripts/preflight-claude.sh @@ -20,6 +20,7 @@ # # Exit codes: # 0 Preflight passed (or skipped — see warnings). +# 1 Missing/invalid Industry, canceled prompt, or azd env save failed. # 4 Marketplace offer not found. # 6 Insufficient quota (Terraform variant only; on Bicep this is a # warning because azd's own ARM preflight already surfaces it). @@ -47,6 +48,13 @@ warn() { printf 'Preflight: %s\n' "$*" >&2 } +industry_only=0 +if [[ $# -gt 0 ]]; then + [[ $# -eq 1 && "$1" = "--industry-only" ]] || + fail 1 "Unknown argument. Use --industry-only to collect attestation before azd up." + industry_only=1 +fi + # Detect which IaC variant the preprovision hook is running under. The hook # always fires from inside the variant folder (infra-bicep/ or # infra-terraform/), so the local azure.yaml tells us which provider azd is @@ -65,7 +73,53 @@ if [ -f "./azure.yaml" ]; then fi fi -# --- 1. Required env vars --------------------------------------------------- +# --- 1. Required Industry attestation -------------------------------------- +# Published values: https://learn.microsoft.com/azure/developer/ai/how-to/deploy-claude-foundry#configure-required-deployment-values +INDUSTRIES=(technology finance healthcare education retail manufacturing government media other) +industry="${INDUSTRY:-}" +save_industry=0 +if [[ -z "${industry//[[:space:]]/}" ]]; then + industry="${CLAUDE_INDUSTRY:-}" + save_industry=1 +fi +if [[ -z "${industry//[[:space:]]/}" ]]; then + if [[ ! -t 0 || ( -n "${CI:-}" && ! "${CI:-}" =~ ^(0|[Ff][Aa][Ll][Ss][Ee])$ ) ]]; then + fail 1 "INDUSTRY is required. Set it before running non-interactively: azd env set INDUSTRY . Valid values: ${INDUSTRIES[*]}." + fi + printf "Anthropic requires your organization's Industry (no default):\n" + for i in "${!INDUSTRIES[@]}"; do + printf ' %s. %s\n' "$((i + 1))" "${INDUSTRIES[$i]}" + done + read -r -p 'Select an Industry number or enter its lowercase value: ' choice || + fail 1 "Industry selection canceled. Set it first: azd env set INDUSTRY ." + if [[ "$choice" =~ ^[1-9]$ ]]; then + industry="${INDUSTRIES[$((choice - 1))]}" + else + industry="$choice" + fi +fi +valid_industry=0 +for value in "${INDUSTRIES[@]}"; do + if [[ "$value" = "$industry" ]]; then valid_industry=1; break; fi +done +if [[ "$valid_industry" -ne 1 ]]; then + fail 1 "Invalid INDUSTRY '$industry'. Choose one of: ${INDUSTRIES[*]} (lowercase)." +fi +if [[ "$save_industry" -eq 1 ]]; then + command -v azd >/dev/null 2>&1 || + fail 1 "Cannot save INDUSTRY: azd is not on PATH. Install azd and rerun from the selected variant folder." + azd env set INDUSTRY "$industry" || + fail 1 "Could not save INDUSTRY to the selected azd environment." +fi +export INDUSTRY="$industry" +if [[ -n "${CLAUDE_INDUSTRY:-}" && "$CLAUDE_INDUSTRY" != "$industry" ]]; then + warn "INDUSTRY overrides legacy CLAUDE_INDUSTRY. Update or remove the legacy value to avoid ambiguity." +fi +if [[ "$industry_only" -eq 1 ]]; then + exit 0 +fi + +# --- Other required env vars ----------------------------------------------- if [ -z "${CLAUDE_ORGANIZATION_NAME:-}" ]; then warn "CLAUDE_ORGANIZATION_NAME is not set. azd will prompt for the 'claudeOrganizationName' Bicep parameter at provision time. To skip the prompt: azd env set CLAUDE_ORGANIZATION_NAME 'Your Org'" fi diff --git a/skills/claude-on-foundry/SKILL.md b/skills/claude-on-foundry/SKILL.md index 16b5f58..2d62090 100644 --- a/skills/claude-on-foundry/SKILL.md +++ b/skills/claude-on-foundry/SKILL.md @@ -64,9 +64,9 @@ The most common failures come from skipping these four checks. Walk through them 4. **Attestation fields.** These are sent to Anthropic on every request and are part of accepting their commercial terms — get them right: - `CLAUDE_ORGANIZATION_NAME` — the customer's legal entity name (no default). - `CLAUDE_COUNTRY_CODE` — ISO-2, default `US`. - - `CLAUDE_INDUSTRY` — **lowercase only**: `technology` | `finance` | `healthcare` | `education` | `retail` | `manufacturing` | `government` | `media` | `other`. + - `INDUSTRY` — **required, no default; lowercase only**: `technology` | `finance` | `healthcare` | `education` | `retail` | `manufacturing` | `government` | `media` | `other`, per the [official guide](https://learn.microsoft.com/azure/developer/ai/how-to/deploy-claude-foundry#configure-required-deployment-values). `preup` prompts once and saves it before required template inputs are resolved. Existing `CLAUDE_INDUSTRY` values migrate automatically. - If `CLAUDE_INDUSTRY` is uppercase or unknown, deployment fails with `AnthropicOrganizationCreationException` — easy to miss because it looks like a transient error. + The hook rejects uppercase or unknown values before provisioning. Set `INDUSTRY` in advance for CI; no prompt occurs when a valid value is already configured. --- @@ -79,6 +79,7 @@ cd infra-bicep # or: cd infra-terraform azd auth login # add --tenant-id if needed azd env new # one env per region + variant combination azd env set CLAUDE_ORGANIZATION_NAME "" +azd env set INDUSTRY "" # or choose once during azd up azd env set AZURE_LOCATION "eastus2" # Pick families — comment out any line to skip that family. @@ -92,7 +93,9 @@ azd env set CLAUDE_CODE_AUTO_INSTALL true azd up ``` -The `preprovision` hook runs `scripts/preflight-claude.ps1` automatically. It is **best-effort**: it warns and continues when `CLAUDE_ORGANIZATION_NAME` / `AZURE_LOCATION` aren't set (azd / Bicep will prompt) or when `az` isn't installed / logged in (the RP will surface any errors at deploy time). It still **hard-fails** on a missing offer in the Anthropic catalog (exit 4) when that check can run — that's the case that turns into an opaque deploy failure otherwise. The quota check is a **hard fail on Terraform** (because `azapi_resource` swallows quota into the opaque `715-123420`) and a **warning on Bicep** (because azd's own ARM preflight already prints `InsufficientQuota` and prompts to continue). Never suggest bypassing the preflight. +The `preup` hook runs the preflight script's Industry-only mode before azd resolves required template inputs: it prompts once and saves `INDUSTRY`, migrates an existing `CLAUDE_INDUSTRY`, or fails explicitly in CI when absent/invalid. For standalone `azd provision`, preconfigure `INDUSTRY` first. + +The `preprovision` hook revalidates Industry and runs the catalog/quota checks. Those checks remain **best-effort**: the hook warns and continues when `CLAUDE_ORGANIZATION_NAME` / `AZURE_LOCATION` aren't set (azd / Bicep will prompt) or when `az` isn't installed / logged in (the RP will surface any errors at deploy time). It still **hard-fails** on a missing offer in the Anthropic catalog (exit 4) when that check can run — that's the case that turns into an opaque deploy failure otherwise. The quota check is a **hard fail on Terraform** (because `azapi_resource` swallows quota into the opaque `715-123420`) and a **warning on Bicep** (because azd's own ARM preflight already prints `InsufficientQuota` and prompts to continue). Never suggest bypassing the preflight. The `postprovision` hook runs `scripts/configure-claude-code.ps1` to wire up Claude Code. The customer can re-run it any time without re-deploying: ```powershell @@ -111,7 +114,7 @@ Match the customer's exact error string to a row. Verify the diagnostic command | Error fingerprint | Root cause | Diagnostic | Fix | |---|---|---|---| -| `AnthropicOrganizationCreationException` / `AnthropicOrganizationCreationFailed` | One of the three attestation fields is missing or `CLAUDE_INDUSTRY` is uppercase. | `azd env get-values \| Select-String CLAUDE_ORGANIZATION_NAME, CLAUDE_COUNTRY_CODE, CLAUDE_INDUSTRY` | `azd env set CLAUDE_INDUSTRY technology` (lowercase). Re-run `azd up`. | +| `AnthropicOrganizationCreationException` / `AnthropicOrganizationCreationFailed` | An attestation field is missing or malformed. | `azd env get-values \| Select-String CLAUDE_ORGANIZATION_NAME, CLAUDE_COUNTRY_CODE, INDUSTRY` | Set your actual lowercase Industry with `azd env set INDUSTRY `. Re-run `azd up`. | | `Project can only be created under AIServices Kind account with allowProjectManagement set to true` | Account property got downgraded. | Check the IaC didn't get edited to remove `allowProjectManagement`. | Restore the template; re-deploy. | | `Marketplace offer ... not found` (from preflight, exit 4) | `CLAUDE_*_MODEL` value is misspelled or that SKU isn't in the catalog. | `./Get-ClaudeCatalog.ps1` and grep the family. | Set `CLAUDE__MODEL` to a name from the catalog. | | `Quota insufficient` (from preflight, exit 6) | Requested capacity + existing usage > per-region limit. | `az cognitiveservices usage list -l --query "[?contains(name.value,'claude-')]"` | Lower `CLAUDE__CAPACITY`, free quota (see soft-delete row), or request a quota bump in the Foundry portal. | diff --git a/tests/test_catalog.py b/tests/test_catalog.py index 6caaf49..07d9c82 100644 --- a/tests/test_catalog.py +++ b/tests/test_catalog.py @@ -12,6 +12,11 @@ ROOT = Path(__file__).resolve().parents[1] PWSH = shutil.which("pwsh") +BASH = ( + r"C:\Program Files\Git\bin\bash.exe" + if os.name == "nt" and Path(r"C:\Program Files\Git\bin\bash.exe").is_file() + else shutil.which("bash") +) @unittest.skipUnless(PWSH, "PowerShell 7 is required for catalog and preflight tests") @@ -28,7 +33,13 @@ def setUp(self) -> None: import sys args = sys.argv[1:] -if args[:2] == ["account", "show"]: +if args[:3] == ["env", "set", "INDUSTRY"]: + if os.environ.get("CLAUDE_TEST_SAVE_FAIL"): + print("Fixture azd env save failed", file=sys.stderr) + sys.exit(1) + with open("industry-saves.jsonl", "a", encoding="utf-8") as saved: + saved.write(json.dumps(args[3:]) + "\\n") +elif args[:2] == ["account", "show"]: print(json.dumps({"tenantId": "example-tenant", "name": "Example", "id": "example-sub"})) elif args[:3] == ["cognitiveservices", "model", "list"]: names = [ @@ -75,20 +86,23 @@ def setUp(self) -> None: encoding="utf-8", ) if os.name == "nt": - (self.work / "az.cmd").write_text( - f'@echo off\n"{sys.executable}" "{fake_cli}" %*\n', encoding="utf-8" - ) - else: - wrapper = self.work / "az" + for name in ("az", "azd"): + (self.work / f"{name}.cmd").write_text( + f'@echo off\n"{sys.executable}" "{fake_cli}" %*\n', encoding="utf-8" + ) + for name in ("az", "azd"): + wrapper = self.work / name wrapper.write_text( - f'#!/bin/sh\nexec "{sys.executable}" "{fake_cli}" "$@"\n', + f'#!/bin/sh\nexec "{Path(sys.executable).as_posix()}" "{fake_cli.as_posix()}" "$@"\n', encoding="utf-8", ) wrapper.chmod(0o755) self.env = { key: value for key, value in os.environ.items() if not key.startswith(("CLAUDE_", "ANTHROPIC_", "AZURE_")) + and key != "INDUSTRY" } + self.env["INDUSTRY"] = "technology" self.env["PATH"] = str(self.work) + os.pathsep + self.env["PATH"] def _run(self, command: str) -> subprocess.CompletedProcess[str]: @@ -102,6 +116,14 @@ def _run(self, command: str) -> subprocess.CompletedProcess[str]: } [pscustomobject]@{ id = 'sample-public-offer' } } +""" + if "CLAUDE_TEST_INDUSTRY_CHOICE" in self.env: + fake_http += """ +function Read-Host { + param([string]$Prompt) + Write-Host 'INDUSTRY_PROMPT' + return $env:CLAUDE_TEST_INDUSTRY_CHOICE +} """ return subprocess.run( [PWSH, "-NoProfile", "-NonInteractive", "-Command", fake_http + command], @@ -181,11 +203,96 @@ def test_preflight_preserves_bicep_arm_preflight_warning(self) -> None: self.assertEqual(result.returncode, 0, result.stdout + result.stderr) self.assertIn("Preflight WARNING", result.stdout) - @unittest.skipIf(os.name == "nt", "Bash preflight scenarios run in Linux CI") + def test_industry_preconfigured_values_skip_prompt_and_save(self) -> None: + for industry in ( + "technology", "finance", "healthcare", "education", "retail", + "manufacturing", "government", "media", "other", + ): + with self.subTest(industry=industry): + self.env.update(INDUSTRY=industry, CI="true") + result = self._preflight("bicep", 25) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertNotIn("INDUSTRY_PROMPT", result.stdout) + self.assertFalse((self.work / "industry-saves.jsonl").exists()) + + def test_industry_missing_in_ci_fails_before_deployment_checks(self) -> None: + self.env.pop("INDUSTRY") + self.env["CI"] = "true" + result = self._preflight("terraform", 25) + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("INDUSTRY is required", result.stdout) + self.assertNotIn("marketplace", result.stdout.lower()) + + def test_industry_noninteractive_shell_explains_how_to_preconfigure(self) -> None: + self.env.pop("INDUSTRY") + self.env.pop("CI", None) + result = self._preflight("bicep", 25) + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("azd env set INDUSTRY", result.stdout) + + def test_industry_menu_choice_is_saved_once_then_reused(self) -> None: + self.env.pop("INDUSTRY") + self.env.pop("CI", None) + self.env["CLAUDE_TEST_INDUSTRY_CHOICE"] = "2" + result = self._preflight("bicep", 25) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(result.stdout.count("INDUSTRY_PROMPT"), 1) + self.assertIn("9. other", result.stdout) + saved = self.work / "industry-saves.jsonl" + self.assertEqual(saved.read_text(encoding="utf-8").splitlines(), ['["finance"]']) + self.env["INDUSTRY"] = "finance" + self.env.pop("CLAUDE_TEST_INDUSTRY_CHOICE") + result = self._preflight("bicep", 25) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(len(saved.read_text(encoding="utf-8").splitlines()), 1) + + def test_industry_legacy_environment_migrates_without_prompt(self) -> None: + self.env.pop("INDUSTRY") + self.env.update(CLAUDE_INDUSTRY="finance", CI="true") + result = self._preflight("terraform", 25) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual( + (self.work / "industry-saves.jsonl").read_text(encoding="utf-8").splitlines(), + ['["finance"]'], + ) + + def test_industry_explicit_value_wins_over_legacy_with_warning(self) -> None: + self.env.update(INDUSTRY="finance", CLAUDE_INDUSTRY="technology") + result = self._preflight("bicep", 25) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("INDUSTRY overrides legacy CLAUDE_INDUSTRY", result.stdout) + self.assertFalse((self.work / "industry-saves.jsonl").exists()) + + def test_industry_invalid_or_uppercase_value_is_not_silently_replaced(self) -> None: + for industry in ("Technology", "NONE", "not-an-industry", " finance "): + with self.subTest(industry=industry): + self.env.update(INDUSTRY=industry, CLAUDE_INDUSTRY="finance") + result = self._preflight("bicep", 25) + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("Invalid INDUSTRY", result.stdout) + self.assertFalse((self.work / "industry-saves.jsonl").exists()) + + def test_industry_save_failure_is_fatal(self) -> None: + self.env.pop("INDUSTRY") + self.env.update(CLAUDE_INDUSTRY="finance", CLAUDE_TEST_SAVE_FAIL="1") + result = self._preflight("terraform", 25) + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("Could not save INDUSTRY", result.stdout) + + def test_industry_only_mode_does_not_run_deployment_checks(self) -> None: + script = str(ROOT / "scripts" / "preflight-claude.ps1").replace("'", "''") + self.env.pop("INDUSTRY") + self.env.update(CLAUDE_INDUSTRY="finance", CI="true") + result = self._run(f"& '{script}' -IndustryOnly; exit $LASTEXITCODE") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertNotIn("AZURE_LOCATION", result.stdout) + self.assertEqual( + (self.work / "industry-saves.jsonl").read_text(encoding="utf-8").splitlines(), + ['["finance"]'], + ) + + @unittest.skipUnless(BASH, "Bash is required") def test_bash_preflight_preserves_the_same_model_offer_and_quota_gates(self) -> None: - bash = shutil.which("bash") - if not bash: - self.skipTest("Bash is required") (self.work / "azure.yaml").write_text( "name: sample\ninfra:\n provider: terraform\n", encoding="utf-8" ) @@ -211,7 +318,7 @@ def test_bash_preflight_preserves_the_same_model_offer_and_quota_gates(self) -> if flag: env[flag] = "1" result = subprocess.run( - [bash, str(ROOT / "scripts" / "preflight-claude.sh")], + [BASH, (ROOT / "scripts" / "preflight-claude.sh").as_posix()], env=env, cwd=self.work, capture_output=True, text=True, encoding="utf-8", timeout=60, ) @@ -219,6 +326,44 @@ def test_bash_preflight_preserves_the_same_model_offer_and_quota_gates(self) -> result.returncode, expected, result.stdout + result.stderr ) + @unittest.skipUnless(BASH, "Bash is required") + def test_bash_industry_required_legacy_validation_and_save_failures(self) -> None: + script = (ROOT / "scripts" / "preflight-claude.sh").as_posix() + for values, expected, text in ( + ({"INDUSTRY": "finance", "CI": "true"}, 0, "Skipping marketplace"), + ({"CLAUDE_INDUSTRY": "finance", "CI": "true"}, 0, "Skipping marketplace"), + ({"CI": "true"}, 1, "INDUSTRY is required"), + ({"INDUSTRY": "Technology"}, 1, "Invalid INDUSTRY"), + ({"CLAUDE_INDUSTRY": "finance", "CLAUDE_TEST_SAVE_FAIL": "1"}, 1, + "Could not save INDUSTRY"), + ): + with self.subTest(values=values): + env = {key: value for key, value in self.env.items() if key != "INDUSTRY"} + env.update(values) + result = subprocess.run( + [BASH, script], env=env, cwd=self.work, stdin=subprocess.DEVNULL, + capture_output=True, text=True, encoding="utf-8", timeout=60, + ) + self.assertEqual(result.returncode, expected, result.stdout + result.stderr) + self.assertIn(text, result.stdout + result.stderr) + + @unittest.skipUnless(BASH, "Bash is required") + def test_bash_industry_only_mode_does_not_run_deployment_checks(self) -> None: + script = (ROOT / "scripts" / "preflight-claude.sh").as_posix() + env = self.env | {"CLAUDE_INDUSTRY": "finance", "CI": "true"} + env.pop("INDUSTRY") + result = subprocess.run( + [BASH, script, "--industry-only"], env=env, cwd=self.work, + stdin=subprocess.DEVNULL, capture_output=True, text=True, + encoding="utf-8", timeout=60, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertNotIn("AZURE_LOCATION", result.stderr) + self.assertEqual( + (self.work / "industry-saves.jsonl").read_text(encoding="utf-8").splitlines(), + ['["finance"]'], + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_industry_templates.py b/tests/test_industry_templates.py new file mode 100644 index 0000000..8c3d9bb --- /dev/null +++ b/tests/test_industry_templates.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +import json +from pathlib import Path +import re +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +INDUSTRIES = { + "technology", "finance", "healthcare", "education", "retail", + "manufacturing", "government", "media", "other", +} + + +class IndustryTemplateTests(unittest.TestCase): + def test_azd_inputs_have_the_same_required_industry_mapping(self) -> None: + bicep = json.loads( + (ROOT / "infra-bicep" / "infra" / "main.parameters.json").read_text() + ) + terraform = json.loads( + (ROOT / "infra-terraform" / "infra" / "main.tfvars.json").read_text() + ) + self.assertEqual(bicep["parameters"]["claudeIndustry"]["value"], "${INDUSTRY}") + self.assertEqual(terraform["claude_industry"], "${INDUSTRY}") + + def test_required_industry_enums_match_in_bicep_and_terraform(self) -> None: + for name in ("main.bicep", "foundry.bicep"): + source = (ROOT / "infra-bicep" / "infra" / name).read_text(encoding="utf-8") + allowed = re.search( + r"@allowed\(\[([^\]]+)\]\)\s*param claudeIndustry string([^\n]*)", + source, + ) + self.assertIsNotNone(allowed, name) + self.assertEqual(set(re.findall(r"'([^']+)'", allowed[1])), INDUSTRIES) + self.assertNotIn("=", allowed[2], "Industry must not have a default") + source = (ROOT / "infra-terraform" / "infra" / "variables.tf").read_text( + encoding="utf-8" + ) + industry = source.split('variable "claude_industry" {', 1)[1] + self.assertNotRegex(industry, r"\bdefault\s*=") + values = re.search(r"contains\(\[([^\]]+)\], var\.claude_industry\)", industry) + self.assertIsNotNone(values) + self.assertEqual(set(re.findall(r'"([^"]+)"', values[1])), INDUSTRIES) + + def test_all_deployments_retain_exact_attestation_properties(self) -> None: + bicep = (ROOT / "infra-bicep" / "infra" / "foundry.bicep").read_text( + encoding="utf-8" + ) + terraform = (ROOT / "infra-terraform" / "infra" / "main.tf").read_text( + encoding="utf-8" + ) + self.assertEqual(len(re.findall(r"industry:\s*claudeIndustry\b", bicep)), 3) + self.assertEqual(len(re.findall(r"industry\s*=\s*var\.claude_industry\b", terraform)), 3) + self.assertEqual(bicep.count("modelProviderData: {"), 3) + self.assertEqual(terraform.count("modelProviderData = {"), 3) + + def test_both_azd_variants_allow_the_preprovision_prompt(self) -> None: + for variant in ("infra-bicep", "infra-terraform"): + source = (ROOT / variant / "azure.yaml").read_text(encoding="utf-8") + preprovision = source.split(" preprovision:", 1)[1].split( + " postprovision:", 1 + )[0] + with self.subTest(variant=variant): + self.assertEqual(preprovision.count("interactive: true"), 2) + self.assertIn("../scripts/preflight-claude.ps1", preprovision) + self.assertIn("../scripts/preflight-claude.sh", preprovision) + + def test_industry_is_collected_before_azd_resolves_required_parameters(self) -> None: + for variant in ("infra-bicep", "infra-terraform"): + source = (ROOT / variant / "azure.yaml").read_text(encoding="utf-8") + preup = source.split(" preup:", 1)[1].split(" preprovision:", 1)[0] + with self.subTest(variant=variant): + self.assertEqual(preup.count("interactive: true"), 2) + self.assertEqual(preup.count("-IndustryOnly"), 2) + self.assertIn("preflight-claude.sh --industry-only", preup) + + +if __name__ == "__main__": + unittest.main()