Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install foundry-agentic-loop@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin foundry-agentic-loop v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install foundry-agentic-loop

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/foundry-agentic-loop/

Extract the ZIP to .github/skills/ in your repo. The folder name must match foundry-agentic-loop for Copilot to auto-discover it.

Skill Files (47)

SKILL.md 12.1 KB
---
name: foundry-agentic-loop
description: 'Build agentic solutions on Microsoft Foundry, GitHub and Azure: hosted agents, toolbox tools and skills, Foundry IQ grounding and a React/FastAPI app. Three modes: rapid prototyping in an existing Foundry project; spec-driven development (SDD), where the foundry-agentic-loop-workflow runs Specify, Implement, Verify and Deploy to create the Foundry project and deploy with azd, or one phase runs alone; and Improve, which refines this skill and the workflow from past runs. Use for Agentic Loop requests and canvas actions, or end-to-end agent solutions from architecture to Azure deployment. Not for isolated Azure administration or unrelated UI edits.'
---

# Foundry Agentic Loop

Coordinate the solution and use `microsoft-foundry` for platform operations. Explicit user choices override defaults. Reuse known context, ask only for missing decisions, read only the references a step needs, and report decisions, blockers and endpoints concisely.

## Bootstrap (once per session)

1. **Foundry skill.** If `microsoft-foundry` is unavailable, ask, then install it (`copilot plugin install azure@awesome-copilot`, or `gh skill install microsoft/azure-skills microsoft-foundry --agent github-copilot --scope project`) and reload skills.
2. **Canvas and workflow.** This plugin ships `foundry-agentic-loop-canvas` and `foundry-agentic-loop-workflow`, listed as `foundry-agentic-loop:<name>` or `<name>`. Call `extensions_manage` with `operation: "list"`. Never install extensions from a URL and never edit Copilot settings files. If one is listed under neither name, tell the user which is missing and that it ships with the plugin, then ask before running `copilot plugin install foundry-agentic-loop@awesome-copilot`; after they approve, call `extensions_reload` once. If one is disabled, tell the user to re-enable it in their extension settings and continue in a new session: running sessions keep it disabled, even after a reload. If one failed, `inspect` it and report its log. Without the canvas, continue in Chat; without the workflow, SDD cannot start, so offer rapid prototyping.
3. **Canvas.** When work starts from Chat, open it once: `open_canvas` with `canvasId: "foundry-agentic-loop-canvas"`, `instanceId: "foundry-agentic-loop"` and `input: { mode }`. Prompts that begin `[Agentic Loop canvas action]` come from the canvas; follow their target, approval and resume instructions literally.

## Choose the mode

| Signal | Mode |
| --- | --- |
| Root `AGENTS.md` has an Agentic Loop section | Its `mode`. Switch only when the user confirms, then rewrite the section |
| Canvas prompt or explicit choice | As stated |
| Existing Foundry project selected or named; fast prototype; no deployment pipeline needed | **Rapid prototyping**: [rapid.md](references/rapid.md) |
| Spec, new Foundry project, azd or IaC, CI-ready repo or full Azure deployment | **SDD**: [sdd.md](references/sdd.md) |
| Improve, learn from runs, or the canvas improve prompt | **Improve**: [improve.md](references/improve.md); measure changes with `node scripts/evals.mjs` (index, then run `--base <commit>`; exit 2 means evals are unavailable, so stop) |
| One named SDD phase, with no run active | Its guide ([Specify](references/specify.md), [Implement](references/implement.md), [Verify](references/verify.md) or [Deploy](references/deploy.md)) with the [SDD defaults](references/sdd.md#sdd-defaults) |

Otherwise ask once with the choices "Rapid prototyping (existing Foundry project)" and "SDD (new project, deployed with azd)".

**Lock it in.** Before any other workspace write (in the rapid preflight, or just before the SDD workflow starts), upsert the section from [agents-md-rapid.md](assets/agents-md-rapid.md) or [agents-md-sdd.md](assets/agents-md-sdd.md) into the root `AGENTS.md`: replace everything between its `foundry-agentic-loop` begin and end markers, or append it, keeping other content; then read it back. The section routes short commands such as `deploy` and locks the mode for Chat, the canvas and the workflow. Azure settings go only in `.azure/deployment-plan.md`, never in `AGENTS.md`. Improve mode never writes it.

## Defaults

- **Agents:** [Foundry hosted agents](references/foundry-hosted-agent.md) exposing the Responses API, Python 3.13, code deployment. Create them through `microsoft-foundry`'s `foundry-agent/create/quick-start-hosted.md` with the **Basic sample**, resolved through that skill, never a guessed URL. Use its advanced workflow only when quick-start cannot support a capability, keeping these defaults. Prompt agents only when requested.
- **Framework:** the Copilot SDK for agents that use runtime skills ([recipe](references/copilot-sdk-foundry.md), [reference agent](references/copilot-sdk-with-toolbox.py)); Microsoft Agent Framework for basic agents and explicit workflows. If a workflow also needs skills, clarify. One framework per agent.
- **Models:** rapid keeps the Basic sample's model deployment, or verifies and reuses a supplied one; SDD defaults to `gpt-5.4-mini` unless the spec needs otherwise. Run the joint placement preflight in [foundry-models.md](references/foundry-models.md) before creating resources. Never hard-code a replacement or silently duplicate a deployment.
- **Tools and knowledge:** one governed [Foundry toolbox](references/foundry-toolbox.md) for built-in tools, MCP connections and agent skills; agents use its endpoint, not hard-coded tool URLs. Private knowledge uses [Foundry IQ](references/foundry-iq-grounding.md) through the toolbox, with citations for supported claims and a deterministic insufficient-evidence response; test both. Add Search only when needed. Reuse run skills the user names from the [run catalog](references/run-skills-catalog.md) instead of regenerating them.
- **App:** React + Vite, FastAPI and FastMCP (streamable HTTP) on Azure Container Apps. Rapid deploys with `az containerapp up --name <app> --source <dir> --resource-group <rg> --environment <env>`; SDD uses [azd](references/azd-layout.md) with a `microsoft.foundry` layer plus a Bicep (AVM) app layer, `remoteBuild: true` and one ACR pulled by managed identity. Add services from the [reference architecture](references/reference-architecture.md) only when the solution needs them.
- **App access:** decide it from the data. When everything the app shows is sample, synthetic or deliberately public, default to no end-user sign-in, even for staff users; services still authenticate with managed identities and need no anonymous-session or identity-verification workarounds. When it shows private, sensitive or user-specific data, ask for the access model before deploying and default to internal ingress or Entra sign-in; anonymous access needs explicit approval. With sign-in, the API pre-authorizes the SPA, the spec states how automated browser tests get a user token, and Implement proves that token path as soon as the app registrations exist.
- **Identity and safety:** managed identities and least-privilege keyless RBAC ([contract](references/rbac-contract.md); [preflight](references/rbac-preflight.md) with [check_rbac_preflight.py](references/check_rbac_preflight.py)). Check management-plane, data-plane and role-assignment rights separately; subscription Owner does not grant Foundry data-plane roles. Plan roles for identities not yet created and verify actual principals after creation. No credentials in browser code or Git; Foundry guardrails on.
- **Observability:** OpenTelemetry from the backend, agents, MCP servers and model calls into one Application Insights connected to the project ([observability.md](references/observability.md)). Sensitive content capture stays off unless approved with redaction and retention controls.

## Workspace files

| File | Holds |
| --- | --- |
| `AGENTS.md` (root) | The mode lock and short-command routes; never Azure settings |
| `README.md` (rapid) or `docs/spec.md` (SDD, from the [spec template](assets/spec-template.md)) | The contract |
| `.azure/deployment-plan.md` | Every Azure setting, in both modes ([template](assets/deployment-plan-template.md)) |
| `.env` (Git-ignored) | What the canvas reads: `FOUNDRY_PROJECT` (full ARM ID, once validated or created), `LOCAL_FRONTEND` and `DEPLOYED_FRONTEND` (verified URLs only). Upsert, keep other keys and read back |
| `docs/LOOP.md` | Lessons ([template](assets/loop-template.md)) |
| `.agentic-loop/runs/<runId>.json` | SDD flight records, written by the workflow |
| `.devcontainer/devcontainer.json` | Optional dev container ([asset](assets/devcontainer.json)) |

## Working rules

- **Contract first.** Freeze service names, environment variables, protocols, endpoints, schemas, auth, streaming, errors and versions ([implementation-contract.md](references/implementation-contract.md)) before parallel work.
- **Integration first.** Pass the [hosted integration checkpoint](references/hosted-integration-checkpoint.md) with a minimal agent before building full orchestration, UI or backend: always a model request, plus a toolbox skill load and a safe MCP call only when the architecture needs them. Record excluded capabilities as `N/A` with the reason, never as passed, and never add unused ones to satisfy the checkpoint.
- **Evidence, not signals.** HTTP 200, exit 0 or `active` never pass alone; require terminal completion, schema-valid output, execution evidence and correlated traces. Fix with bounded diagnostics, not unchanged redeployments.
- **Wait by completion.** Provisioning, deployments, role-assignment propagation and agent readiness end when their command or status check says so: run the command synchronously with a long initial wait, or poll its status every 30-60 s against a stated deadline. Never chain fixed sleeps; keep coding while Azure works.
- **Subagents.** Before the checkpoint, parallelize only research and preflight. After it, give each worker a bounded goal, exclusive workspace-relative files or folders, skill references, verified context, the contract, acceptance checks and stop conditions. One owner (the coordinator, or the SDD phase lead) holds the contract and the shared files: `azure.yaml`, `infra/`, `docs/`, `.env`, `.azure/`, `.agentic-loop/`, `AGENTS.md` and the root lockfiles. Keep teams small, avoid recursive delegation, serialize shared Azure mutations and integrate centrally; worker success is not acceptance. Delegation grants no extra approval. Without subagents, work sequentially and say so.
- **Safety.** Reuse resources; confirm billable, security or compliance changes; delete without approval only a resource this build created whose provisioning failed; never sign in for the user; never report an unverified deployment as successful.
- **Workspace boundary.** Builds stay inside the workspace: read lessons only from its own `docs/LOOP.md`, scaffold from the Foundry samples and these references, and use code from other folders only when the user names them. Only improve mode reads past runs elsewhere.
- **Work IQ context.** Only when the user or a canvas prompt asks for it, query the `workiq` MCP server before clarifying questions, fold in only the requirements that matter, cite each by source type and confirm them. Never copy confidential content, personal data or secrets into the workspace; if Work IQ is unavailable or needs consent, say so and continue without it.
- **Companions and SDKs.** Verify installed SDK APIs against the latest stable release (or the newest stable one the build's package index serves, recording the gap) and lock versions before generating code; package sources beat stale guidance. Consult the [build catalog](references/build-skills-catalog.md) only for needed capabilities; respect pins, ask before installs and route third-party skill defects upstream.

## Lessons

Right after a fix is verified (the failing probe or an equivalent boundary check reruns successfully; an edit, commit or deployment alone is not resolution), upsert a lesson in the workspace's `docs/LOOP.md` from the [template](assets/loop-template.md) before unrelated work, then read it back. Keep user notes, update matching lessons instead of duplicating them, and never include secrets, raw `.env` values or payloads. The coordinator, or the SDD phase lead, owns writes; workers report evidence. Lessons never authorize skill edits or weaker gates; improve mode applies them with approval.
assets/
agents-md-rapid.md 1.1 KB
<!-- foundry-agentic-loop:begin mode=rapid -->
## Agentic Loop: rapid prototyping

This workspace is a rapid prototype in an existing Foundry project. For build requests, load the `foundry-agentic-loop` skill and follow its `references/rapid.md`. Short commands:

| Command | Step |
| --- | --- |
| `run` | Start the backend and frontend dev servers and report their URLs |
| `test` | Run the local acceptance, contract and E2E tests |
| `add agent`, `add tool`, `add skill` | Extend against the contract, then rerun the checkpoint probes |
| `deploy` | Redeploy changed agents and MCP servers and rerun their probes, then ask before deploying the app to the target in `.azure/deployment-plan.md` |
| `improve` | Improve mode |
| `convert to SDD` | Confirm, derive the spec with Specify `reverse`, switch this section to SDD and start the workflow |

- The contract lives in the root `README.md`, lessons in `docs/LOOP.md` and Azure settings only in `.azure/deployment-plan.md`, never here.
- This section locks the build mode. Change it only when the user explicitly confirms a switch.
<!-- foundry-agentic-loop:end -->
agents-md-sdd.md 1.4 KB
<!-- foundry-agentic-loop:begin mode=sdd -->
## Agentic Loop: SDD workflow

This workspace is built with spec-driven development. For build requests and the short commands below, load the `foundry-agentic-loop` skill and follow its `references/sdd.md`; it checks the live run first and resumes a running or paused run instead of starting a second one.

| Command | Step |
| --- | --- |
| `status` | Report the live run from `dynamic_workflows_manage`, then the gate issues in its `.agentic-loop/runs/` record |
| `approve`, `resume` | Resume the paused run with `resumeFromRunId` |
| `deploy` | If a run is active, deploy only through it: at `approve-deploy-v1` or `approve-deploy-r<n>[-a<k>]-v1`, summarize it and resume it once approved; at any other pause, report where it stopped and resolve that first. With no active run, run the Deploy phase guide, which asks before `azd up` |
| `specify`, `implement`, `verify` | With no run active, run that phase guide on the existing artifacts |
| `build <brief>` | Offer to resume a running or paused run; otherwise start a new `foundry-agentic-loop-workflow` run |
| `improve` | Improve mode |

- The spec and contract live in `docs/spec.md`, lessons in `docs/LOOP.md` and Azure settings only in `.azure/deployment-plan.md`, never here.
- This section locks the build mode. Change it only when the user explicitly confirms a switch.
<!-- foundry-agentic-loop:end -->
deployment-plan-template.md 3.0 KB
# Azure deployment plan

> The single home for this workspace's Azure settings, in both modes. Written by Specify (SDD) or the rapid preflight, then kept current as resources change; Implement and Deploy read it. Rapid fills only the rows that apply and skips those marked SDD. Contains no secrets.

## Target

| Field | Value |
| --- | --- |
| Solution | `{solution}` |
| Mode | `sdd` or `rapid`, matching the root `AGENTS.md` lock |
| Foundry project | SDD: created by the `foundry` layer, ARM ID recorded after provisioning. Rapid: the existing project's ARM ID and endpoint |
| azd environment (SDD) | `{solution}-{stage}` (at most 20 characters) |
| Subscription | `{name}` (`{id}`), tenant `{tenantId}` |
| Signed-in principal | `{upn or appId}` (`{objectId}`) |
| Resource groups | SDD app: `rg-{environment}` (new; `az group exists` returned false). Foundry: {the provider's group, recorded after provisioning; rapid: the project's group} |
| Region | Preferred `{region}` → chosen `{region}`, because {placement evidence}. Rapid: the project's region |
| Agent scaffold (SDD) | `azd ai agent init .` with the Basic sample manifest `{manifestUrl}`, in an empty `.scaffold` folder, then moved into place |
| Infra (SDD) | `azure.yaml` layers: `foundry` (`microsoft.foundry`) → `app` (Bicep with AVM, `infra/app`) |

## Models

| Deployment | Model and version | SKU | Capacity | Quota evidence |
| --- | --- | --- | --- | --- |
| `gpt-5.4-mini` | `gpt-5.4-mini` {version} | GlobalStandard | {TPM} (~{c} concurrent E2E cases at {tokens} per case) | {free quota in region} |

## Resources

Rapid lists only the resources it reuses or creates, with `—` as the layer.

| Resource | Layer | Purpose | SKU | Identity | Est. monthly cost |
| --- | --- | --- | --- | --- | --- |
| Foundry account and project | foundry | Agents, models, toolbox | S0 | system | usage |
| Container Apps environment and apps | app | Frontend, backend, MCP | Consumption | user-assigned | {estimate} |
| Container Registry | app | Images (remote build) | Basic | AcrPull by identity | {estimate} |
| Log Analytics and Application Insights | app | Telemetry, connected to the project | Pay-as-you-go | — | {estimate} |

## RBAC

Verdict from the foundry-agentic-loop RBAC preflight: `READY` or `BLOCKED`.

| Principal | Role | Scope | Created by |
| --- | --- | --- | --- |
| {identity} | {role} | {scope} | app layer |
| {deployer} (`AZURE_PRINCIPAL_ID`) | Monitoring Metrics Publisher | Application Insights | app layer |

{When BLOCKED: the ready-to-run grant block for an owner.}

## Environment variables (SDD)

Implement sets these with `azd env set`, `AZURE_RESOURCE_GROUP` first, one command per variable.

| Variable | Value |
| --- | --- |
| `AZURE_RESOURCE_GROUP` | `rg-{environment}` |
| `AZURE_SUBSCRIPTION_ID` | `{id}` |
| `AZURE_LOCATION` | `{region}` |
| `AZURE_TENANT_ID` | `{tenantId}` |
| `AZD_AGENT_SKIP_ACR` | `false` only when agents deploy as containers |

## Risks and decisions

| Item | Decision | Evidence |
| --- | --- | --- |
| {cost, quota, security or compliance item} | {decision} | {source} |
devcontainer.json 0.8 KB
{
  "name": "Agentic Loop",
  "image": "mcr.microsoft.com/devcontainers/universal:2",
  "features": {
    "ghcr.io/devcontainers/features/github-cli:1": {},
    "ghcr.io/devcontainers/features/azure-cli:1": {
      "installBicep": true
    },
    "ghcr.io/azure/azure-dev/azd:0.2.0": {
      "version": "1.35.1",
      "extensions": "azure.ai.agents,azure.ai.toolboxes,azure.ai.skills,azure.ai.connections"
    },
    "ghcr.io/devcontainers/features/copilot-cli:1": {}
  },
  "postCreateCommand": "pipx install uv==0.13.1 || pip install --user uv==0.13.1",
  "customizations": {
    "vscode": {
      "extensions": [
        "ms-azuretools.azure-dev",
        "ms-azuretools.vscode-bicep",
        "TeamsDevApp.vscode-ai-foundry",
        "ms-windows-ai-studio.windows-ai-studio"
      ]
    }
  }
}
loop-template.md 1.3 KB
# Agentic Loop lessons

Verified lessons from building this workspace. Improve mode turns them into skill and workflow changes, only with approval.

<!--
How to upsert (the coordinator or SDD phase lead writes; workers report evidence):
- Write right after a fix is verified: the failing probe, or an equivalent boundary check, reran successfully. An edit, commit or deployment alone is not resolution.
- Update the matching row instead of adding a duplicate, revisit earlier proposals and keep user notes.
- Separate verified app fixes from untested skill proposals, and measurements from estimates. When no skill change is supported, say so in the outcome line.
- Never include secrets, raw .env values or request and response payloads.
- Read the file back after each write.
- Status: proposed, adopted (applied by improve mode), validated (a later run confirmed the benefit) or rejected.
-->

## YYYY-MM-DD <solution>, <rapid | SDD>

Outcome: <what was built and verified, or "No skill change is supported.">

| Observation and evidence | Proposed skill change (file, section) | Expected benefit | Regression check | Status |
| --- | --- | --- | --- | --- |
| <symptom, root cause, and the rerun that proved the fix> | <`references/<file>.md`, section, or none> | <measured, or marked as an estimate> | <eval ID or probe> | proposed |
spec-template.md 4.0 KB
# {Solution} — Specification

> Last updated: {YYYY-MM-DD} · Scenario: {canvas scenario or n/a} · Deployment plan: [.azure/deployment-plan.md](../.azure/deployment-plan.md)

## 1. Summary

One paragraph: what is built, for whom, why, and the measurable outcome.

## 2. Goals and non-goals

**Goals:** {measurable outcomes}

**Non-goals:** {explicitly out of scope}

## 3. Users and scenarios

| Persona | Scenario | Success criteria |
| --- | --- | --- |
| {persona} | {scenario} | {observable outcome} |

## 4. Functional requirements

| ID | Requirement | Acceptance criteria (EARS) | Priority |
| --- | --- | --- | --- |
| FR-001 | The system shall {capability} so that {benefit}. | When {trigger}, the {component} shall {response}. | Must |

## 5. Non-functional requirements

| Category | Requirement | Measure |
| --- | --- | --- |
| Performance | {e.g. first token < 3 s at p95} | {how measured} |
| Security | Keyless managed identities; least-privilege RBAC; no secrets in code | RBAC contract rows |
| Responsible AI | Foundry guardrails on; grounded answers cite sources; refusal when evidence is insufficient | Evaluation metrics |
| Observability | OpenTelemetry from every component into one Application Insights | Correlated trace |
| Privacy and compliance | {data classification, residency} | {control} |
| Cost | {budget or main drivers} | {estimate} |

## 6. Architecture

{Two or three sentences on components, data flow and trust boundaries.}

```mermaid
flowchart LR
  U[User] --> FE[Frontend<br/>React + Vite] --> BE[Backend<br/>FastAPI]
  BE --> AG[Hosted agent<br/>Responses API]
  AG --> TB[Foundry toolbox<br/>skills · MCP · Foundry IQ]
  AG --> M[(Model)]
  FE & BE & AG -. OTel .-> AI[(Application Insights)]
```

## 7. Agents

| Agent | Purpose | Framework | Protocol | Model | Toolbox, skills and tools | Grounding | Guardrails |
| --- | --- | --- | --- | --- | --- | --- | --- |
| {name} | {job} | Copilot SDK or MAF | Responses | {deployment} | {toolbox and items} | {Foundry IQ source or none} | {policy} |

## 8. Components and Azure services

| Component | Technology | Azure service and SKU | Identity |
| --- | --- | --- | --- |
| {frontend} | React + Vite | Container Apps (Consumption) | {uami} |

## 9. Data

Entities, fields, ownership, retention and classification. Name the sample or synthetic data source and where it lives.

**Seed rules.** For every seeded record a rule reads, freeze the values the rule needs (dates, counts, amounts, window anchors) and each tool's result for that ID, including empty results. Labels and names carry no decision facts.

## 10. Implementation contract (frozen)

Service names, environment variables, endpoints, protocols, request, response and error schemas, streaming, auth and versions. Change this section before changing any code that depends on it.

**Decision rules.** Each rule reads only frozen facts or tools in the consuming agent's list, and a decision tool has a frozen derivation. A window names its anchor date; trigger categories are closed lists. Guards, routing and sort keys cover every enum value plus null or invalid agent output. Recompute each scenario's expected outcome from these rules. Tables keep the header's cell count. Describe credentials and `Authorization` values in words, never as literals.

## 11. Workstreams

| # | Workstream | Goal | Exclusive files | Depends on | Acceptance |
| --- | --- | --- | --- | --- | --- |
| 1 | {name} | {goal} | `src/{dir}/**` | Foundation | {checks} |

At most four. The phase lead owns the foundation, the contract, shared configuration and integration.

## 12. Verification plan

| Requirement | Check | Level | Evidence |
| --- | --- | --- | --- |
| FR-001 | {probe} | unit, contract, E2E, evaluation or trace | {artifact} |

**Evaluation:** {n} scenarios from section 3 with expected behaviour; metrics: task adherence, groundedness (when grounded) and safety.

## 13. Assumptions and open questions

| # | Item | Default or decision | Owner | Status |
| --- | --- | --- | --- | --- |
| 1 | {assumption} | {default taken} | {owner} | assumed |
evals/
evals.json 94.0 KB
{
  "skill_name": "foundry-agentic-loop",
  "evals": [
    {
      "id": 1,
      "mode": "sdd",
      "capabilities": [
        "architecture",
        "grounding",
        "placement",
        "contract",
        "sdk-versions"
      ],
      "targets": [
        "references/specify.md",
        "references/foundry-models.md",
        "references/implementation-contract.md",
        "references/foundry-iq-grounding.md",
        "references/copilot-sdk-foundry.md"
      ],
      "risk": "medium",
      "prompt": "Post-process this Agentic Loop SDD specification into concise architecture and planning guidance: Build a Zava HR Concierge on Microsoft Foundry. Use a GitHub Copilot SDK hosted agent, enterprise HR documents in Foundry IQ, one toolbox MCP endpoint, a React frontend, a Python backend, ingestion, and azd/Bicep deployment. Multiple engineers will implement components in parallel. The target subscription is not known to have model, Search, hosted-agent, or preview capacity in East US 2. Do not add document-level or caller-aware authorization. Return a Markdown policy addendum only; do not create or deploy resources.",
      "expected_output": "A concise policy addendum that applies the one-toolbox/one-knowledge-base architecture, joint live placement preflight, frozen implementation contract, latest-stable SDK compatibility, citations, and deterministic no-source refusal without caller-aware document controls.",
      "files": [],
      "expectations": [
        "The addendum defaults to one governed toolbox MCP endpoint and one Foundry IQ knowledge base.",
        "Before persisting azd environment values, placement jointly validates the exact model/version/SKU/capacity, Azure AI Search SKU, hosted-agent availability, and required preview features.",
        "The plan freezes a shared cross-component contract before parallel work and includes service names, environment variables, protocol/endpoint, MCP schemas, model configuration, response/citation/refusal shapes, and runtime/package versions.",
        "Supported claims require citations, and no cited evidence produces a deterministic refusal.",
        "The addendum does not require caller identity propagation, group/persona filters, entitlement knowledge bases, or document allow/deny evaluation.",
        "The SDK guidance resolves and verifies the latest stable github-copilot-sdk API before generating code."
      ]
    },
    {
      "id": 2,
      "mode": "shared",
      "capabilities": [
        "sdk-versions",
        "companion-skills"
      ],
      "targets": [
        "references/copilot-sdk-foundry.md",
        "references/build-skills-catalog.md"
      ],
      "risk": "low",
      "prompt": "Review this generated Python reference against the latest stable github-copilot-sdk release and return a corrected code block plus a short compatibility note. The current code is: `client = CopilotClient(); await client.start(); session = await client.create_session(config); await session.send_and_wait({\"prompt\": prompt}); await client.stop()`. Preserve tool, model, provider, and permission options from `config`. Prefer safe lifecycle cleanup. Also state what to do if an installed companion skill's example disagrees with the package API.",
      "expected_output": "Lifecycle-safe code verified against the latest stable package API, plus accurate Python/session/response-event compatibility and upstream-defect guidance.",
      "files": [],
      "expectations": [
        "The latest stable github-copilot-sdk release is resolved from the official package source before API guidance is produced.",
        "The corrected code follows the session creation, prompt sending, response/event, and lifecycle APIs exposed by that resolved release.",
        "The compatibility note states the resolved package version and supported Python version.",
        "Compatibility checks are assigned to the generated application's implementation or CI workflow, not to the agent skill itself.",
        "If companion guidance conflicts with the resolved package API, the package source is authoritative and the defect is handled through an upstream issue or PR rather than a local third-party skill patch."
      ]
    },
    {
      "id": 3,
      "mode": "sdd",
      "capabilities": [
        "placement",
        "companion-skills",
        "rbac"
      ],
      "targets": [
        "references/specify.md",
        "references/foundry-models.md",
        "references/build-skills-catalog.md",
        "references/rbac-preflight.md"
      ],
      "risk": "medium",
      "prompt": "Prepare the Specify preflight for an Agentic Loop SDD run that needs gpt-5.4-mini at 100K TPM, Azure AI Search, Foundry hosted agents, Application Insights, and least-privilege RBAC. The project has copilot-sdk and microsoft-foundry installed from moving main branches, but their freshness is unknown. Explain how to validate placement and companion skills before persisting azd environment values. Return Markdown only and do not install or modify third-party skills.",
      "expected_output": "A live joint placement check, preferred/deployed location recording, dynamic skill existence and freshness checks, supported refresh workflow, and use of microsoft-foundry/rbac rather than standalone azure-rbac.",
      "files": [],
      "expectations": [
        "Placement is one live subscription-specific decision covering model/version/SKU/100K capacity, Search SKU, hosted agents, and required preview features before azd environment persistence.",
        "The plan records preferred and deployed locations and immediately reconciles spec, plan, and deployment-plan artifacts when they differ.",
        "Installed skill source URL, version/tree SHA, pin state, and update status are inspected; installation alone is not treated as freshness.",
        "Catalog candidates are validated against the target repository before use, and stale approved unpinned skills are refreshed through gh skill update.",
        "The output does not modify third-party installed skills and directs defects to an upstream issue or PR.",
        "Foundry RBAC guidance uses the maintained microsoft-foundry/rbac sub-skill rather than standalone azure-rbac."
      ]
    },
    {
      "id": 4,
      "mode": "rapid",
      "capabilities": [
        "rbac",
        "contract",
        "observability",
        "deploy",
        "integration-checkpoint"
      ],
      "targets": [
        "references/rapid.md",
        "references/rbac-preflight.md",
        "references/hosted-integration-checkpoint.md",
        "references/observability.md",
        "references/implementation-contract.md"
      ],
      "risk": "high",
      "prompt": "Use Agentic Loop rapid prototyping to plan a basic service-desk agent and React/FastAPI app in my existing Foundry project. I am subscription Owner but data-plane access is unknown, and the backend managed identity has not been created. Keep the Basic sample's model, do not use runtime skills or private document retrieval, and do not provision anything. Return only a concise architecture and acceptance checklist.",
      "expected_output": "A concise plan using MAF, the sample's model and source deployment, with consolidated deployer permission gaps, planned runtime assignments, a README implementation contract, a hosted checkpoint limited to the required boundaries, correlated privacy-preserving telemetry, and separate approval for cloud app deployment.",
      "files": [],
      "expectations": [
        "Uses Microsoft Agent Framework for the basic agent, Python 3.13, Responses API and the Basic sample's model without substituting a hard-coded model or region.",
        "Checks management-plane and data-plane access separately; Owner is not accepted as proof of data-plane access.",
        "Checks ability to assign planned runtime roles without requiring a not-yet-created identity to already have effective permissions.",
        "Records shared service, environment, protocol/schema, authentication, streaming/error and dependency contracts under ## Implementation contract in the root README, and plans to record the hosted checkpoint verdict under ## Hosted checkpoint.",
        "Acceptance verifies a correlated backend/agent/tool trace in Application Insights, with sensitive content capture off unless explicitly approved and controlled.",
        "Preserves local E2E testing and a separate approval gate before frontend/backend deployment with `az containerapp up --name <app> --source <dir> --resource-group <rg> --environment <env>`.",
        "Does not require Search, Foundry IQ, the foundry-agentic-loop-workflow, a new Foundry project or an audit of every installed skill.",
        "The hosted integration checkpoint proves only the required boundaries: model inference always, toolbox skill loading only when runtime skills are required and an MCP call only when an MCP tool is required. It records each excluded boundary (here runtime skills) as N/A with a reason, and does not add an unused skill or switch frameworks to satisfy the checkpoint."
      ]
    },
    {
      "id": 5,
      "mode": "shared",
      "capabilities": [
        "runtime-skills",
        "grounding",
        "companion-skills",
        "placement"
      ],
      "targets": [
        "references/run-skills-catalog.md",
        "references/foundry-iq-grounding.md",
        "references/copilot-sdk-foundry.md",
        "references/foundry-models.md",
        "references/build-skills-catalog.md"
      ],
      "risk": "medium",
      "prompt": "Plan a skill-driven incident assistant using the existing incident-postmortem runtime skill and private operational runbooks. The user experience is React with FastAPI. There is an existing Foundry project, a pinned Copilot SDK build skill and no approved Search resource yet. Do not install, update, rewrite skills or provision anything; return concise guidance covering reuse, grounding, compatibility, placement and acceptance.",
      "expected_output": "A Copilot SDK plan that reuses the named runtime skill, preserves its governed version, respects the pinned build skill, validates SDK APIs and joint placement conditionally, and includes cited and insufficient-evidence acceptance cases.",
      "files": [],
      "expectations": [
        "Selects Copilot SDK for the skill-driven agent and distinguishes the build skill from the incident-postmortem runtime skill.",
        "Resolves incident-postmortem from the run catalog rather than generating a replacement and plans to publish/version it in the agent's toolbox.",
        "Respects the pinned companion skill and does not update it, patch third-party copies or audit unrelated installed skills.",
        "Checks installed SDK APIs and locks compatible dependency versions.",
        "Plans governed grounding with citations and an explicit insufficient-evidence response, testing both paths.",
        "Checks new resource availability, model/SKU/quota and required service placement jointly without changing the existing project, model or region silently.",
        "Does not provision an unapproved Search resource or send runtime test prompts.",
        "Plans the deployed identity, named skill load, required MCP call and model request checkpoint before full application implementation."
      ]
    },
    {
      "id": 6,
      "mode": "shared",
      "capabilities": [
        "lessons",
        "deploy-approval"
      ],
      "targets": [
        "SKILL.md",
        "assets/loop-template.md",
        "references/rapid.md"
      ],
      "risk": "medium",
      "prompt": "Finish the local acceptance handoff for an Agentic Loop build. The UI-to-agent E2E checks and correlated telemetry verification have passed, and the verified local frontend URL has just been saved as LOCAL_FRONTEND in root .env. During this build, a backend/frontend API schema mismatch caused a failed E2E test; updating both sides to the contract in the root README.md fixed it and the test passed. Existing docs/LOOP.md contains a user-authored note and a proposed early contract check that we tried successfully. There are no measured time or token savings. Return the proposed docs/LOOP.md update and handoff only; do not run services, modify installed skills or deploy anything.",
      "expected_output": "An evidence-grounded docs/LOOP.md update after the .env write, preserving prior content, evaluating the earlier lesson, and proposing generalizable changes to the foundry-agentic-loop skill with regression checks, followed by the separate app deployment approval question.",
      "files": [],
      "expectations": [
        "Creates or updates docs/LOOP.md after writing LOCAL_FRONTEND and before the frontend/backend deployment approval pause.",
        "Preserves the existing user-authored note and prior entries rather than replacing the feedback file.",
        "Records the observed schema mismatch, its correction and passing E2E result without inventing commands, file paths or measurements.",
        "Proposes a specific improvement to foundry-agentic-loop instructions with a target section, expected benefit and regression check, rather than only summarizing the application.",
        "Revisits the earlier early-contract-check proposal and records its supported outcome.",
        "Separates proposals from validated changes and does not claim measured time or token savings.",
        "Does not disclose secrets or raw .env contents, rewrite installed skills or treat docs/LOOP.md as authorization to relax approval gates.",
        "Retains the explicit confirmation gate before backend/frontend deployment."
      ]
    },
    {
      "id": 7,
      "mode": "shared",
      "capabilities": [
        "integration-checkpoint",
        "rbac",
        "observability",
        "contract"
      ],
      "targets": [
        "references/hosted-integration-checkpoint.md",
        "references/copilot-sdk-foundry.md",
        "references/rbac-contract.md",
        "references/implementation-contract.md"
      ],
      "risk": "high",
      "prompt": "Use Agentic Loop to plan a skill-driven operations assistant with one existing toolbox skill, one read-only MCP tool, a React UI and FastAPI backend. We previously built the whole app before finding hosted identity failures. The agent principal does not exist yet. Return the ordered implementation and acceptance plan only; do not provision or invoke anything. Keep Python 3.13, the Basic sample's model and code deployment.",
      "expected_output": "An integration-first plan that blocks full app work until a minimal deployed skill/tool/model path passes, distinguishes planned from actual identity checks, and persists four separate endpoint contracts without reserved-variable collisions.",
      "files": [],
      "expectations": [
        "Consults hosted-integration-checkpoint.md and copilot-sdk-foundry.md at the relevant steps rather than inventing platform mechanics.",
        "Orders minimal MCP/toolbox and hosted-agent deployment before full UI, backend or orchestration implementation.",
        "Plans to discover the actual agent principal after creation and verifies principal/resource/role combinations separately from the toolbox connection identity.",
        "Distinguishes the full project endpoint, model API base URL, hosted Responses endpoint and toolbox MCP endpoint; persists discovered values and uses a nonreserved project-endpoint variable.",
        "Requires actual deployed-identity skill loading, MCP execution and model-request evidence with terminal completion and schema-valid output before expansion.",
        "Configures hosting and Copilot runtime telemetry before deployment and requires correlated hosting, model and required tool spans at the checkpoint rather than deferring telemetry until full application work.",
        "Preserves Python 3.13, code deployment, the sample's model and the separate frontend/backend deployment approval gate.",
        "Does not execute deployment or runtime probes for this plan-only request."
      ]
    },
    {
      "id": 8,
      "mode": "shared",
      "capabilities": [
        "integration-checkpoint",
        "rbac",
        "diagnostics"
      ],
      "targets": [
        "references/hosted-integration-checkpoint.md",
        "references/rbac-contract.md",
        "references/foundry-hosted-agent.md"
      ],
      "risk": "high",
      "prompt": "Our minimal hosted agent is active. The CLI exits zero and returns HTTP 200, but its SSE stream ends in response.failed after a model 403. The same prompt works with my az login credentials. An agent identity now exists, the toolbox connection has a different identity, and the application uses a full project URL stored in FOUNDRY_PROJECT_ENDPOINT. Can we proceed with the full app? Give a bounded diagnostic and acceptance plan only. Include tests for missing upstream fields, JSON versus SSE, concurrent response IDs and async tool-call limits.",
      "expected_output": "A blocked checkpoint with targeted identity/endpoint and direct-versus-SDK diagnosis, bounded propagation retries, safe correlation evidence and exact contract tests instead of repeated full deployments.",
      "files": [],
      "expectations": [
        "Explicitly blocks full application expansion; active, CLI zero and HTTP 200 do not override response.failed.",
        "Requires response.completed for SSE or final completed status for JSON, schema-valid output and actual required skill/tool/model execution evidence.",
        "Uses the actual deployed principal and verifies project Foundry User, model-host account Cognitive Services OpenAI User and authenticated telemetry emitter Monitoring Metrics Publisher where applicable, without blanket grants.",
        "Keeps the agent-to-toolbox and toolbox-connection-to-downstream identities distinct and does not substitute developer credentials.",
        "Checks the reserved endpoint-variable collision and moves the application full project URL to a validated nonreserved variable without overwriting platform configuration.",
        "Compares minimal direct and SDK requests under the same hosted identity/context, uses bounded RBAC propagation retries and avoids unchanged redeployments.",
        "Requests response, hosted and SDK session, agent-version and service request IDs in safe diagnostics, without tokens, sensitive bodies or opaque caller-context values.",
        "Tests missing fields, JSON/SSE errors, interleaved response-ID matching and tool-budget reservation before asynchronous dispatch.",
        "Includes failure rendering, persistence, export, mobile and keyboard acceptance and cleanup restricted to task-created debug sessions."
      ]
    },
    {
      "id": 9,
      "mode": "shared",
      "capabilities": [
        "sdk",
        "auth",
        "mcp",
        "packaging"
      ],
      "targets": [
        "references/copilot-sdk-foundry.md",
        "references/copilot-sdk-with-toolbox.py",
        "references/foundry-toolbox.md",
        "references/foundry-hosted-agent.md"
      ],
      "risk": "medium",
      "prompt": "Write an implementation recipe, not a deployment, for our Python 3.13 code-deployed Copilot SDK agent. Use the versioned Agentic Loop reference as a source-checked baseline and explain what to verify in the installed SDK/runtime. Model requests use a discovered /openai/v1/ URL; toolbox requests pass on the first turn but fail after token expiry. Concurrent hosted calls carry different x-agent-foundry-call-id and x-agent-user-id headers. Remote pip resolution also fails, although our locked Linux wheels are available locally. Preserve code deployment and our pinned dependencies.",
      "expected_output": "A version-aware OpenAI Responses provider recipe with refreshed workload tokens and request-isolated allowlisted context for model and toolbox, plus a conditional reproducible bundled-dependency fallback.",
      "files": [],
      "expectations": [
        "Names the source-checked SDK reference version without claiming the whole recipe was deployment-tested; checks installed signatures and logs the actual running SDK/runtime versions before troubleshooting.",
        "Uses type openai, wire_api responses and the discovered /openai/v1/ base, with bearer_token_provider for refresh rather than a startup token.",
        "Forwards each request's x-agent-foundry-call-id unchanged to model and toolbox requests, never forwards x-agent-user-id outbound and never trusts arbitrary browser headers as platform identity.",
        "Explains that model bearer-token callbacks do not refresh static MCP headers and chooses a supported refreshing or lifecycle-managed request-scoped MCP transport.",
        "Isolates concurrent caller contexts and tests token renewal without modifying global mutable headers or weakening tool approvals.",
        "Uses bundling only after remote-resolution diagnosis; retains Python 3.13 and source-code deployment with pinned hash-verified Linux-compatible dependencies.",
        "Includes extracted packages and compatible runtime assets in the flat deployment archive while excluding them from Git and pytest discovery.",
        "Does not copy a macOS virtualenv, discard hashes, upgrade pinned dependencies silently or claim upload/active status proves runtime success.",
        "Requires the hosted checkpoint to pass after the changed bundled artifact is deployed, without performing that deployment in this recipe-only task."
      ]
    },
    {
      "id": 10,
      "mode": "shared",
      "capabilities": [
        "subagents",
        "integration-checkpoint",
        "contract"
      ],
      "targets": [
        "SKILL.md",
        "references/implementation-contract.md",
        "references/hosted-integration-checkpoint.md"
      ],
      "risk": "medium",
      "prompt": "Use Agentic Loop to plan parallel implementation of a skill-driven operations assistant with React, FastAPI and a Foundry hosted agent/toolbox. Coding subagents are available, but the minimal hosted checkpoint has not passed yet. The UI and API share schemas; all components share .env and a lockfile. Explain what can run in parallel now and after the checkpoint, worker ownership and integration gates. Return a plan only; do not launch workers or provision resources.",
      "expected_output": "A dependency-aware subagent plan that preserves integration-first ordering, gives workers non-overlapping ownership and complete context, and reserves shared configuration, approvals and final acceptance for coordinated integration.",
      "files": [],
      "expectations": [
        "Limits pre-checkpoint parallel work to independent research/preflight checks and blocks full application implementation until hosted proof passes.",
        "Plans concurrent substantial frontend, backend or agent/tool tasks only after freezing the shared contract and resolving dependencies.",
        "Gives each worker bounded goals, exclusive files, relevant skill references, verified context, acceptance checks and stop conditions.",
        "Assigns shared schemas/contracts, .env, lockfiles and deployment configuration to one owner rather than allowing conflicting edits.",
        "Keeps the worker set small, honors configured limits, and avoids recursive delegation or duplicating worker tasks.",
        "Serializes dependent work and shared Azure mutations without extending provisioning or deployment approval.",
        "Requires worker evidence and central cross-component verification; retains hosted proof, local E2E acceptance, docs/LOOP.md and separate app-deployment approval.",
        "Does not actually launch subagents or provision anything for this plan-only request."
      ]
    },
    {
      "id": 11,
      "mode": "shared",
      "capabilities": [
        "observability",
        "integration-checkpoint",
        "privacy"
      ],
      "targets": [
        "references/observability.md",
        "references/copilot-sdk-foundry.md",
        "references/hosted-integration-checkpoint.md"
      ],
      "risk": "high",
      "prompt": "Our Python Copilot SDK hosted agent completes its minimal skill/tool/model probe. The Foundry project has Application Insights linked and APPLICATIONINSIGHTS_CONNECTION_STRING is set. We see hosting requests but no model or tool spans. CopilotClient currently has no telemetry options; two hosted requests can run concurrently. Can we pass the Agentic Loop checkpoint and build the UI? Give a bounded configuration and acceptance plan only. We have not approved a new collector or Azure resources; do not provision, deploy, invoke agents or change dependencies.",
      "expected_output": "A blocked telemetry checkpoint and version-aware two-producer configuration plan, with a verified OTLP export route, correct exporter identity scope, privacy-preserving trace correlation and deployed span evidence before expansion.",
      "files": [],
      "expectations": [
        "Blocks full application expansion despite terminal probe completion, a linked project and hosting spans because required model/tool trace evidence is missing.",
        "Uses the telemetry section of copilot-sdk-foundry.md and checks actual hosting/Copilot SDK/runtime versions rather than claiming every installed version supports current source behavior.",
        "Configures the host's supported observability once and explicit Copilot runtime telemetry without duplicate providers or runtime clients.",
        "Uses a real reachable OTLP HTTP receiver with a supported onward export path, not a connection string, ordinary ingestion URL or gRPC-only endpoint as the runtime receiver.",
        "Records the destination, export routes and actual exporting identities; distinguishes direct Application Insights emitter scope from native OTLP collector DCR scope without unconditional grants.",
        "Reuses an approved route or reports the missing route as a blocker; does not silently provision a collector or change dependencies.",
        "Preserves W3C traceparent/tracestate and request-local parent relationships across concurrent runtime/tool callbacks, separately from Foundry authentication caller context.",
        "Keeps both content-capture settings off and avoids sensitive explicit logs; checks sampling, graceful flush and bounded ingestion delay.",
        "Requires deployed hosting, model and required tool spans in the destination's actual schema, with correct trace relationships and agent/version identification, not mocks or exporter startup messages.",
        "Keeps diagnosis bounded and does not invoke probes, deploy or repeatedly redeploy unchanged artifacts for this plan-only request."
      ]
    },
    {
      "id": 12,
      "mode": "shared",
      "capabilities": [
        "lessons"
      ],
      "targets": [
        "SKILL.md",
        "assets/loop-template.md"
      ],
      "risk": "low",
      "prompt": "We are using Agentic Loop and have not built the frontend or written LOCAL_FRONTEND. A hosted model request failed because our app read an account-only project URL. We switched to the nonreserved full project endpoint variable and reran the same deployed probe: it now completes with schema-valid output. docs/LOOP.md already has a user note and a proposed endpoint-contract check. No time or token savings were measured, and no skill changes have been applied. Return the immediate next action and proposed docs/LOOP.md update only; do not deploy, edit installed skills or implement the UI.",
      "expected_output": "Immediate lesson capture before further implementation, updating the existing endpoint lesson with the verified fix and evidence while preserving the user note and proposal status.",
      "files": [],
      "expectations": [
        "Calls for updating the workspace's docs/LOOP.md now, without waiting for local acceptance, LOCAL_FRONTEND or full application success.",
        "Records the failure, supported cause, nonreserved endpoint fix and supplied passing deployed-probe evidence without inventing identifiers, commands or measurements.",
        "Updates the matching endpoint lesson rather than duplicating it and preserves the user-authored note.",
        "Includes a proposed skill change/section, expected benefit, regression check and status, distinguishing the verified app fix from an unvalidated skill proposal.",
        "Requires read-back verification of the write and explicit reporting of persistence failures.",
        "Does not claim all other hosted checkpoint requirements passed or authorize implementation, deployment or installed-skill edits."
      ]
    },
    {
      "id": 13,
      "mode": "shared",
      "capabilities": [
        "lessons",
        "subagents"
      ],
      "targets": [
        "SKILL.md",
        "assets/loop-template.md"
      ],
      "risk": "low",
      "prompt": "During an Agentic Loop build, a worker reports that a retry fix was committed and the agent deployed successfully, but the original failing probe still times out. Another worker fixed an independent schema mismatch and reran its failing contract test successfully. Both workers want to edit the shared docs/LOOP.md now, and local acceptance is tomorrow. Explain the immediate lesson-capture decisions only; do not execute anything.",
      "expected_output": "Keep the timeout unresolved, immediately record the verified schema fix through the coordinator, and preserve shared-file ownership and evidence boundaries.",
      "files": [],
      "expectations": [
        "Does not treat a commit or successful deployment as resolution of the still-failing timeout.",
        "Requires successful rerun of the failing probe or equivalent boundary verification before marking that failure resolved.",
        "Captures the independently verified schema fix immediately rather than waiting for local acceptance or every failure to be fixed.",
        "Has workers report evidence promptly to the coordinator, who serializes shared docs/LOOP.md updates instead of allowing competing edits.",
        "Preserves existing lessons, excludes secrets and separates application-fix verification from skill-change validation."
      ]
    },
    {
      "id": 14,
      "mode": "sdd",
      "capabilities": [
        "mode-selection",
        "workflow-start",
        "preflight"
      ],
      "targets": [
        "SKILL.md",
        "references/sdd.md"
      ],
      "risk": "high",
      "prompt": "Use Agentic Loop to build and deploy a claims triage assistant for Contoso Insurance with spec-driven development. Use subscription 00000000-0000-0000-0000-000000000000 and region eastus2. Adjusters upload a claim summary; the agent classifies severity, checks the policy rules skill and routes the claim. Start the delivery now.",
      "expected_output": "SDD mode: a read-only preflight, at most one clarification round, then run_dynamic_workflow for foundry-agentic-loop-workflow with a self-contained brief and the Azure target, followed by a short report of the run ID, canvas progress and checkpoints without polling.",
      "files": [],
      "expectations": [
        "Chooses SDD mode, not rapid prototyping, because the user asks for spec-driven development and deployment.",
        "Runs read-only preflight checks (az account, azd auth status, azd Foundry extension, microsoft-foundry availability) and reports all gaps together without installing or upgrading tools unasked.",
        "Asks at most one round of clarifying questions, only about decisions that change the spec.",
        "Starts run_dynamic_workflow with name foundry-agentic-loop-workflow and args containing a self-contained brief, subscriptionId, location eastus2 and an environmentName of at most 20 characters.",
        "Does not create Foundry resources, scaffold code or run azd provision in Chat before the run; the workflow phases do that.",
        "Does not pass limits the user did not specify.",
        "Reports the run ID, that the Foundry Agentic Loop canvas shows progress and that the run pauses at approve-spec-v1 and approve-deploy-v1, and does not poll the run."
      ]
    },
    {
      "id": 15,
      "mode": "sdd",
      "capabilities": [
        "canvas-action",
        "workflow-gates",
        "lessons"
      ],
      "targets": [
        "references/sdd.md",
        "references/verify.md"
      ],
      "risk": "medium",
      "fixture": "sdd-paused",
      "prompt": "[Agentic Loop canvas action] The foundry-agentic-loop-workflow run wr_42 is paused at blocked-verify-r2. Investigate the Verify gate issues, fix the root cause and record evidence. Do not resume the run.",
      "expected_output": "Reads the run's gate issues, the artifacts and docs/LOOP.md, fixes and re-verifies the root cause, records a lesson and leaves the run paused for the canvas to resume.",
      "files": [
        "AGENTS.md",
        "docs/spec.md",
        "docs/verify.md",
        "docs/LOOP.md",
        ".agentic-loop/runs/wr_42.json",
        "src/backend/routing.py"
      ],
      "expectations": [
        "Reads the run with dynamic_workflows_manage inspect-run and the gate issues before changing code.",
        "Reads docs/verify.md, the related artifacts and docs/LOOP.md for context.",
        "Fixes the root cause in the smallest scope and reruns the failing check, then the related suite, reporting real results.",
        "Upserts a docs/LOOP.md lesson only after the fix is verified.",
        "Does not call run_dynamic_workflow or resume the run, because the canvas prompt says not to.",
        "Does not weaken tests, thresholds or gates, skip the phase or report unverified checks as passed."
      ]
    },
    {
      "id": 16,
      "mode": "sdd",
      "capabilities": [
        "canvas-action",
        "spec",
        "placement"
      ],
      "targets": [
        "references/specify.md",
        "assets/spec-template.md",
        "assets/deployment-plan-template.md",
        "references/foundry-models.md"
      ],
      "risk": "medium",
      "prompt": "[Agentic Loop canvas action] The foundry-agentic-loop-workflow run wr_7 is paused for spec approval. Apply this feedback to docs/spec.md, and to .azure/deployment-plan.md when affected: use swedencentral for EU data residency and add a requirement that adjusters can export the triage decision as PDF. Do not resume the run.",
      "expected_output": "Consistent edits to the spec and deployment plan, with a new EARS requirement, updated placement and verification plan, and no resume.",
      "files": [],
      "expectations": [
        "Adds the export requirement in EARS form with a new stable ID, an acceptance criterion and a verification plan entry.",
        "Updates the region in both docs/spec.md and .azure/deployment-plan.md and reruns or flags the joint placement check for swedencentral before persisting AZURE_LOCATION.",
        "Keeps existing requirement IDs and the frozen implementation contract consistent; contract changes are explicit.",
        "Summarizes the changes, including any cost or quota impact.",
        "Does not resume the run and does not start implementation, provisioning or deployment."
      ]
    },
    {
      "id": 17,
      "mode": "sdd",
      "capabilities": [
        "workflow-gates",
        "deploy-approval"
      ],
      "targets": [
        "references/sdd.md",
        "references/deploy.md"
      ],
      "risk": "high",
      "prompt": "My foundry-agentic-loop-workflow run wr_9 is paused at approve-deploy-v1. Approve it and deploy now.",
      "expected_output": "A concise pre-deployment summary followed by resuming the same run, without deploying directly from Chat.",
      "files": [],
      "expectations": [
        "Summarizes the resources, cost drivers, security exposure and region from the deployment plan and docs/verify.md before resuming.",
        "Resumes with run_dynamic_workflow and resumeFromRunId wr_9 because the user explicitly asked.",
        "Does not run azd up, azd deploy or az containerapp commands directly in Chat.",
        "Does not start a new run or raise workflow limits without a workflow_limit_reached error and approval.",
        "Reports that the run continues in the canvas and notifies on completion, without polling."
      ]
    },
    {
      "id": 18,
      "mode": "improve",
      "capabilities": [
        "improve",
        "evidence",
        "approval",
        "eval"
      ],
      "targets": [
        "references/improve.md"
      ],
      "risk": "medium",
      "fixture": "improve-history",
      "prompt": "Improve the Agentic Loop skill and workflow from our last runs in this repository.",
      "expected_output": "Read-only analysis of flight records, docs/LOOP.md, workflow runs and sessions, clustered by root cause, with minimal evidence-backed diffs and regression checks, applied only after approval.",
      "files": [
        "docs/LOOP.md",
        ".agentic-loop/runs/wr_101.json",
        ".agentic-loop/runs/wr_117.json",
        ".agentic-loop/runs/wr_123.json"
      ],
      "expectations": [
        "Builds candidate clusters from .agentic-loop/runs/*.json, docs/LOOP.md and dynamic_workflows_manage runs and inspect-run, then uses time-bounded session_store_sql queries with LIMIT only to confirm or quantify them, never reading raw events.jsonl transcripts end to end.",
        "Clusters findings by root cause and ranks them by frequency and impact, keeping only clusters with evidence from two runs or one verified severe failure.",
        "Proposes minimal diffs with target file and section, expected benefit and a regression eval, preferring tightening or deleting text.",
        "Never proposes weakening approvals, RBAC, safety or evidence gates, or adding secrets or tenant-specific values.",
        "Does not edit any file before approval; in a solution repository, applies changes as project overrides under .github/skills instead of editing installed plugin files.",
        "After applying, selects regression cases with `node <skill>/scripts/evals.mjs index --target <file>` and runs them with `run ... --base <base-commit>`; accepts only no regressions with every new or changed case passing, reports failures that also fail at the base as pre-existing, and stops with \"evals unavailable\" if the runner exits 2.",
        "Marks matching docs/LOOP.md lessons adopted only after a passing regression run, and validated only after a later real run confirms the benefit."
      ]
    },
    {
      "id": 19,
      "mode": "rapid",
      "capabilities": [
        "mode-selection",
        "rbac",
        "integration-checkpoint",
        "local-e2e"
      ],
      "targets": [
        "references/rapid.md",
        "references/rbac-preflight.md",
        "references/hosted-integration-checkpoint.md"
      ],
      "risk": "medium",
      "prompt": "Quickly prototype a retail returns assistant in my Foundry project proj-retail-dev. I want to try it locally today; no pipelines.",
      "expected_output": "Rapid prototyping in the existing project, driven from Chat, with project validation, RBAC preflight, the hosted checkpoint and a locally tested app.",
      "files": [],
      "expectations": [
        "Chooses rapid prototyping and does not start foundry-agentic-loop-workflow or create a new Foundry project.",
        "Validates the named project and records its ARM ID as FOUNDRY_PROJECT in the root .env only after validation.",
        "Runs the RBAC preflight with management-plane, data-plane and role-assignment checks reported together.",
        "Keeps the Basic sample's model deployment and passes the hosted integration checkpoint before building the full app.",
        "Tests the app locally end to end, upserts LOCAL_FRONTEND with the verified URL and treats cloud deployment as optional with separate approval."
      ]
    },
    {
      "id": 20,
      "mode": "shared",
      "capabilities": [
        "bootstrap",
        "extensions"
      ],
      "targets": [
        "SKILL.md"
      ],
      "risk": "low",
      "prompt": "Start an Agentic Loop session. extensions_manage list shows foundry-agentic-loop-canvas loaded from the foundry-agentic-loop plugin, but no foundry-agentic-loop-workflow.",
      "expected_output": "Explains that the workflow is missing, asks before reinstalling the plugin, reloads once after approval and opens the canvas once.",
      "files": [],
      "expectations": [
        "Does not reinstall or duplicate foundry-agentic-loop-canvas.",
        "Tells the user foundry-agentic-loop-workflow is missing and asks before running copilot plugin install foundry-agentic-loop@awesome-copilot; never calls install_extension or edits Copilot settings files, and calls extensions_reload once only after approval.",
        "If installation fails, inspects the extension and reports its log instead of retrying blindly.",
        "Opens the canvas once with canvasId foundry-agentic-loop-canvas and instanceId foundry-agentic-loop.",
        "Ensures microsoft-foundry is available, asking before installing it."
      ]
    },
    {
      "id": 21,
      "mode": "sdd",
      "capabilities": [
        "rbac",
        "mcp",
        "auth",
        "infra"
      ],
      "targets": [
        "references/azd-layout.md",
        "references/rbac-contract.md",
        "references/hosted-integration-checkpoint.md"
      ],
      "risk": "high",
      "prompt": "Our Agentic Loop SDD claims solution provisioned, but the hosted integration checkpoint fails. The toolbox's `tools/list` against our keyless MCP server returns HTTP 403, and that container app's authentication shows `allowedApplications: []`. The first hosted invoke returns 500 while the agent downloads its skill. Our script that grants Azure roles to the agent blueprint principal fails with `PrincipalTypeNotSupported`. The Foundry account and project are in `rg-claims-dev-foundry`, the container apps are in `rg-claims-dev`, and the app layer's role assignments on the account failed. We will re-provision the app layer later in Verify. Give a bounded fix plan only; do not run anything.",
      "expected_output": "A fix plan that grants runtime roles to the agent instance identity only, adds project Foundry User for skill download, persists the MCP allow-list through an azd env var, Bicep and a live patch, scopes account grants to the Foundry resource group, keeps deployed images across re-provision and retries to a deadline instead of redeploying.",
      "files": [],
      "expectations": [
        "Reads the `instance_identity` and `blueprint` principal and client IDs from `azd ai agent show <agent> --output json` and grants Azure roles to the runtime instance principal only, never the blueprint.",
        "Grants the runtime instance identity Foundry User on the project so the skill download succeeds, plus only the other RBAC contract rows the agent needs, without blanket or subscription-wide grants.",
        "Allows the instance and blueprint client IDs of every agent whose toolbox reaches the MCP app, stores the sorted list in an azd env var that Bicep maps to `allowedApplications`, and patches the live `authConfigs/current`; it explains the 403 by the empty list.",
        "Creates the account and project role assignments in a module scoped to the Foundry resource group (`resourceGroup(aiResourceGroupName)` from `AZURE_FOUNDRY_RESOURCE_GROUP`) or in the postdeploy hook, not in the app resource group.",
        "Sets each container app image from `${SERVICE_<NAME>_IMAGE_NAME=}` with a placeholder fallback, so the planned re-provision keeps the deployed images.",
        "Puts the post-deploy grants in an idempotent `postdeploy` hook that checks before creating, then retries the first hosted invoke with backoff until a fixed deadline instead of redeploying unchanged code.",
        "Records the actual resource groups and regions, including `AZURE_FOUNDRY_RESOURCE_GROUP`, in the deployment plan."
      ]
    },
    {
      "id": 22,
      "mode": "sdd",
      "capabilities": [
        "spec",
        "seed-data"
      ],
      "targets": [
        "references/specify.md",
        "assets/spec-template.md"
      ],
      "risk": "medium",
      "prompt": "Review this Agentic Loop spec excerpt before the Specify gate and return only the corrected rules and seed rows. Today is 2026-10-08. (1) Seed S2: a prior claim dated 2021-05-14, 'outside 36 months; bureau count 1'; `get_bureau_reports` defaults to `months=36`. (2) Seed S7 has loss type `water_damage (flood)` and seed S8 has `water_damage`. (3) Fraud signal WEATHER fires on any 'weather-related' loss type. (4) Fraud signal OVER_LIMIT fires when the claimed amount exceeds `limit_usd` from `get_coverage`, but only the adjudicator agent has `get_coverage`. (5) Fraud signal RECENT_POLICY fires when the policy started within 30 days. (6) Routing queues claims by `max(decision.fraud_score, assessment.fraud_score)`, sorted by `routing.priority`; `decision` is null when the adjudicator fails. (7) The two-column RBAC table (Principal | Role) has the row `| backend MI | AcrPull | grant after provision |`. (8) The toolbox note says to call the MCP server with `Authorization: Bearer <access-token>`.",
      "expected_output": "Executable seed and decision rules: frozen counts and anchored windows, closed trigger lists, inputs traced to the consuming agent's tools, null-safe routing, well-formed tables, credentials described in words and recomputed seed outcomes.",
      "files": [],
      "expectations": [
        "S2 states bureau count 0 for the default 36-month window, because 2021-05-14 falls outside it, or explicitly freezes a different window.",
        "Loss types come from one closed enum and labels carry no decision facts: S7 and S8 either share one value with the flood detail in a separate frozen field, or flood becomes its own enum value, never a parenthetical such as `water_damage (flood)`.",
        "WEATHER fires on a closed list of loss types instead of an open 'weather-related' category.",
        "OVER_LIMIT reads only the fraud agent's own tools or frozen facts, for example by adding `get_coverage` to its tool list or freezing `limit_usd` per seed, not a tool that only the adjudicator has.",
        "RECENT_POLICY names its anchor date, such as the loss date, and each seed freezes the dates the rule depends on.",
        "Routing defines the result when `decision` is null or invalid, and its sort key covers every enum value plus null.",
        "Every RBAC row has as many cells as its header, whether the table keeps two columns or adopts the plan template's columns, and the post-provision instruction moves out of the row.",
        "The `Authorization` header is described in words, as the Bearer scheme with an access token, not written as a literal.",
        "Each seed's expected outcome is recomputed from the corrected rules: which signals fire and why, plus the score and routing wherever the excerpt supplies the weights they need; missing weights are flagged, not invented."
      ]
    },
    {
      "id": 23,
      "mode": "shared",
      "capabilities": [
        "dependencies",
        "sdk-versions"
      ],
      "targets": [
        "SKILL.md",
        "references/implementation-contract.md",
        "references/implement.md"
      ],
      "risk": "medium",
      "prompt": "Implement is pinning Python dependencies for a hosted agent and a FastMCP server. The official index has github-copilot-sdk 1.0.17 and fastmcp 4.0.11 as the latest stable releases. The build uses an approved package proxy that serves only up to github-copilot-sdk 1.0.16 and fastmcp 4.0.10, plus a 1.0.17rc1 pre-release of the SDK. A `--generate-hashes` lock compiled through the proxy contains `--hash=md5:` entries, and the ACR remote build fails. The spec's Runtime versions row says `azure-identity` 'latest stable'. What exactly should we pin and record? Return the plan only.",
      "expected_output": "Pins the newest stable releases the build's index serves (never a pre-release), inspects that API, keeps only sha256/sha384/sha512 hashes, replaces 'latest' with exact versions and records the gap to the official latest release.",
      "files": [],
      "expectations": [
        "Resolves the latest stable releases from the official package index and also checks what the build's proxy index serves before pinning.",
        "Pins github-copilot-sdk 1.0.16 and fastmcp 4.0.10, the newest stable releases the proxy serves, and never 1.0.17rc1 or another pre-release.",
        "Inspects the API of the pinned github-copilot-sdk release instead of assuming the 1.0.17 API.",
        "Records the gap between each official latest release and its pinned version in the contract or implementation notes.",
        "Regenerates or filters the hashed lock so it keeps only sha256, sha384 or sha512 hashes, matching pip's allowed hash algorithms.",
        "Replaces 'latest stable' with an exact version for every direct dependency and exact image tags, and confirms the build's index or registry serves each pin."
      ]
    },
    {
      "id": 24,
      "mode": "sdd",
      "capabilities": [
        "e2e",
        "concurrency"
      ],
      "targets": [
        "references/verify.md",
        "references/deploy.md"
      ],
      "risk": "medium",
      "prompt": "Verify is about to run 10 multi-turn E2E claim scenarios against `gpt-5.4-mini` (GlobalStandard, capacity 100). One scenario took 3 minutes, and its Responses `usage` totaled 60K tokens. An earlier run at concurrency 10 hit 429s and produced AGENT_ERROR results. How should we run and record the E2E suite now, and what does Deploy reuse?",
      "expected_output": "Parallel E2E at a measured concurrency c = 4, computed from capacity, measured tokens and duration, recorded in docs/verify.md and reused by Deploy, with a 429 after retries counted as a failure.",
      "files": [],
      "expectations": [
        "Runs the E2E cases in parallel at a measured concurrency, not sequentially by default or at a hard-coded concurrency of 1.",
        "Computes c = max(1, ⌊0.8 × TPM × minutes per case ÷ tokens per case⌋) with TPM = capacity × 1000, which gives c = 4 for these measurements.",
        "Takes tokens per case and duration from one measured case's Responses `usage` and timing, not from a guess.",
        "Records c and its inputs (TPM, tokens per case and minutes per case) in `docs/verify.md`.",
        "Treats a 429 that persists after retries as a test failure, not as a pass or a skip.",
        "Has Deploy rerun the E2E suite at the concurrency recorded in `docs/verify.md`."
      ]
    },
    {
      "id": 25,
      "mode": "sdd",
      "capabilities": [
        "scaffold",
        "azd"
      ],
      "targets": [
        "references/azd-layout.md",
        "references/implement.md"
      ],
      "risk": "medium",
      "prompt": "Implement must scaffold the first hosted agent, `fraud`, from the Basic sample into our existing SDD workspace. It already has `docs/`, a root `azure.yaml` with the foundry layer and `.azure/deployment-plan.md`. Everything runs with `--no-prompt`, and `azd ai agent init .` failed with 'confirmation declined; app was not initialized'. A teammate suggests adding `--force` or running `azd init -t` with the sample template first. Give the exact steps only.",
      "expected_output": "Scaffolds in an empty `.scaffold` folder, moves the sample to `src/agents/fraud`, merges root files, copies only the azd environment, unstages and removes `.scaffold` and writes `.agentignore`, without `--force` or `azd init -t`.",
      "files": [],
      "expectations": [
        "Runs `azd ai agent init .` with `--no-prompt`, `-t <azure.yaml URL>` from the sample's `initCommand` (not the deprecated `-m <manifestUrl>`) and `--agent-name fraud` inside a new, empty `.scaffold` folder.",
        "Rejects both `--force` and `azd init -t <template>`.",
        "Moves the sample folder to `src/agents/fraud`, points the service's `project` there, and merges `azure.yaml` into the existing root file instead of overwriting it.",
        "Copies only `.scaffold/.azure/config.json` and the environment folder into `.azure/`, never moving or overwriting `.azure/` or `deployment-plan.md`.",
        "Unstages the files init git-staged, deletes `.scaffold`, and confirms that `git status --short` lists no `.scaffold` path.",
        "Writes `.agentignore` in the agent folder so the code package carries runtime files only."
      ]
    },
    {
      "id": 26,
      "mode": "sdd",
      "capabilities": [
        "deploy",
        "azd",
        "rbac",
        "mcp"
      ],
      "targets": [
        "references/deploy.md",
        "references/azd-layout.md"
      ],
      "risk": "high",
      "prompt": "Deploy an approved SDD solution whose `azure.yaml` defines `infra.layers` named `foundry` and `app`, and whose postdeploy hook grants the agents' runtime roles and MCP allow-lists. `azd provision --preview` fails. After `azd up`, `azd show -o json` lists the services without endpoints, and `azd ai agent monitor fraud` fails with 'A session ID is required for log streaming'. The backend uses internal ingress. Give the Deploy steps and checks only.",
      "expected_output": "Per-layer previews, `azd up` with exit code and hook readback, endpoints from `azd env get-values`, HTTPS probes of public endpoints only, session-scoped monitoring and E2E at the recorded concurrency.",
      "files": [],
      "expectations": [
        "Previews each layer with `azd provision --preview <layer> --no-prompt` (foundry and app) instead of a plain `--preview`.",
        "Runs `azd up --no-prompt`, records its exit code, and reads back the postdeploy effects: role assignments with `az role assignment list --assignee <principalId> --all` and each MCP app's `authConfigs/current`.",
        "Runs `azd hooks run postdeploy --no-prompt` when a grant or allow-list is missing, then checks again.",
        "Reads endpoints from `azd env get-values` (`SERVICE_<NAME>_URI`, `AGENT_<NAME>_RESPONSES_ENDPOINT`) instead of `azd show`.",
        "Probes only public endpoints over HTTPS and does not treat the unreachable internal backend as a failure.",
        "Reads the session ID from the invoke's `Session:` line and runs `azd ai agent monitor <agent> --session-id <id>`.",
        "Reruns the E2E suite at the concurrency recorded in `docs/verify.md`, plus every check Verify deferred to Deploy."
      ]
    },
    {
      "id": 27,
      "mode": "sdd",
      "capabilities": [
        "workflow-gates",
        "observability",
        "rbac"
      ],
      "targets": [
        "references/verify.md",
        "references/observability.md"
      ],
      "risk": "high",
      "prompt": "You are the reviewer for the Verify gate. `docs/verify.md` says every acceptance criterion passes and that the backend request span shares an `operation_Id` with both hosted agents. `az containerapp revision list` for `ca-backend` shows a new revision created during Verify, after the backend was deployed to get that span, because local telemetry export failed without Monitoring Metrics Publisher on Application Insights. Should the gate pass? Return the verdict and the required fixes only.",
      "expected_output": "A failed Verify gate: a backend revision created after the passed Implement gate runs a new image, so the backend was deployed during Verify, which the phase forbids. The fix proves backend telemetry locally with the deployer's Monitoring Metrics Publisher grant.",
      "files": [],
      "expectations": [
        "Fails the gate because a backend revision created during Verify runs a new image, which breaks Verify's rule against deploying the frontend or backend, regardless of the passing trace.",
        "Confirms from the container app revisions created after the passed Implement gate (its time is in the flight record), not only from `docs/verify.md`, whether any frontend or backend revision runs a new image; same-image revisions from re-provisioning do not count.",
        "Requires the backend telemetry check to pass locally or carry an approved waiver, rather than relying on a backend deployed in Verify.",
        "Fixes local export by granting the deployer Monitoring Metrics Publisher on Application Insights, as the deployment plan's RBAC rows specify.",
        "Does not weaken the gate or accept a deferral to Deploy for a check that can run locally."
      ]
    },
    {
      "id": 28,
      "mode": "shared",
      "capabilities": [
        "eval",
        "responses-api"
      ],
      "targets": [
        "references/foundry-hosted-agent.md",
        "references/verify.md"
      ],
      "risk": "medium",
      "prompt": "Our hosted fraud agent (Python, `azure-ai-agentserver-responses` 2.2.0) calls three MCP tools through its toolbox per turn and returns `TextResponse(context, request, text=text)`. Foundry task_adherence scores it 3/10 with 'no TOOL_CALLS provided', yet the traces show that the tool calls ran. Explain the cause, then give the handler change and a unit test, with code only where needed.",
      "expected_output": "Explains that evaluators score only output items, then streams a function_call and function_call_output item per tool call before the final message with ResponseEventStream, and adds a unit test.",
      "files": [],
      "expectations": [
        "Explains that evaluators score only the response's output items, so a bare `TextResponse` hides the tool calls.",
        "Checks the installed `azure-ai-agentserver-responses` API before writing the handler.",
        "Builds the response with `ResponseEventStream(response_id=context.response_id, request=request)`, emitting the created and in-progress events first.",
        "Emits a function call item and a function call output item with the matching `call_id` for each tool call (`output_item_function_call` and `output_item_function_call_output`).",
        "Emits the final message item last, so `output_text` stays the answer, and then emits completed.",
        "Adds a unit test that the events contain one call/output pair per tool call and end with the message, then reruns the evaluation."
      ]
    },
    {
      "id": 29,
      "mode": "sdd",
      "capabilities": [
        "eval"
      ],
      "targets": [
        "references/verify.md"
      ],
      "risk": "medium",
      "prompt": "In Verify we ran `azd ai agent eval run --agent fraud` and then `azd ai agent eval run --agent adjudicator` in the same azd environment, without `--config`. The adjudicator results seem to use the fraud agent's criteria. What went wrong, and what is the correct per-agent sequence?",
      "expected_output": "Isolates each agent's evaluation in its own config file: generate per agent with `--out-file`, run with `--config`, check the reported agent and version, keep the config with the results and rerun the adjudicator.",
      "files": [],
      "expectations": [
        "Identifies that both runs resolved an implicit, shared eval definition from the azd environment instead of an explicit per-agent config, so the adjudicator run used the fraud agent's criteria.",
        "For each agent, runs `azd ai agent eval generate --agent <svc> --dataset tests/eval/dataset.jsonl --out-file tests/eval/<svc>.eval.yaml --evaluator builtin.task_adherence --evaluator builtin.intent_resolution`, adding `--evaluator builtin.groundedness` only when that agent is grounded.",
        "Then runs `azd ai agent eval run --agent <svc> --config tests/eval/<svc>.eval.yaml`, one config per agent.",
        "Checks that the run's `Agent: <name> v<N>` line names the intended agent and version before accepting the results.",
        "Keeps each agent's config file with its results, discards the mismatched adjudicator results and reruns that agent's evaluation."
      ]
    },
    {
      "id": 30,
      "mode": "sdd",
      "capabilities": [
        "workflow-gates",
        "resume"
      ],
      "targets": [
        "references/sdd.md"
      ],
      "risk": "medium",
      "prompt": "Our SDD workflow run paused at `blocked-implement-r1` with the issue \"Implement · integration ended twice without a report, likely a provider error\". Since then the agent is deployed and the backend tests pass. What should we do before resuming, and what will the resumed round do?",
      "expected_output": "Treats the pause as a provider failure, checks the session log and the current state read-only, records the evidence, resumes the same run and explains that round 2 continues from the current state without repeating finished work.",
      "files": [],
      "expectations": [
        "Identifies the pause as a provider or reporting failure, not an application defect, and checks the session log for the error.",
        "Checks the current state read-only (`azd env get-values`, hosted agent versions, Container App revisions) instead of starting over.",
        "Records the existing evidence in `docs/implementation.md` and the lesson in `docs/LOOP.md` before resuming.",
        "Resumes the same run with `run_dynamic_workflow` and `resumeFromRunId` when the user asks, rather than starting a new run.",
        "Explains that Implement round 2 continues from the current state, its review first re-checks the issue, and finished steps replay from the journal.",
        "Does not rebuild, reprovision or redeploy unchanged services."
      ]
    },
    {
      "id": 31,
      "mode": "sdd",
      "capabilities": [
        "workflow-monitoring"
      ],
      "targets": [
        "references/sdd.md"
      ],
      "risk": "medium",
      "prompt": "Our SDD workflow run has shown `running` in Implement for 95 minutes. `list_agents` shows no background agents, the flight record hasn't changed and the credit total is the same as an hour ago. It looks stalled. Should we cancel and restart it?",
      "expected_output": "Explains why these signals don't show a stall, checks live activity in the canvas Build tab and the workspace, and leaves cancellation to the user without cancelling, pausing or restarting.",
      "files": [],
      "expectations": [
        "Does not cancel, pause, restart or resume the run, or start a new one.",
        "Explains that workflow subagents don't appear in `list_agents` or `read_agent`.",
        "Explains that the flight record and credit totals change only when a step ends, and that one Implement step can run for over an hour.",
        "Checks live activity in the canvas Build tab and recent workspace or Azure changes.",
        "Reports the evidence and leaves any cancellation to the user."
      ]
    },
    {
      "id": 32,
      "mode": "sdd",
      "capabilities": [
        "spec",
        "workflow-gates"
      ],
      "targets": [
        "references/specify.md"
      ],
      "risk": "low",
      "prompt": "The third Specify review of our customer-service SDD run flagged three issues: the idempotency store's eviction algorithm isn't specified, the retry backoff for Search calls isn't frozen and the spec doesn't define the SQLite layout for conversation history. The brief mentions none of these, and the spec is already 1,500 lines. How should the fixer respond?",
      "expected_output": "Classifies the findings as implementation details left to Implement, adds no mechanisms for them, confirms the cross-component contract is frozen and tightens the oversized spec.",
      "files": [],
      "expectations": [
        "Classifies the eviction algorithm, retry backoff and storage layout as internal details owned by Implement, because the brief doesn't require them.",
        "Does not add sections or mechanisms to the spec to satisfy these findings.",
        "Confirms the spec freezes the cross-component interfaces, schemas, auth, errors and decisions.",
        "Notes that a 1,500-line spec is disproportionate (most fit in about 600 lines) and tightens existing text instead of expanding it.",
        "Records why the findings aren't blocking, so the next review can confirm it."
      ]
    },
    {
      "id": 33,
      "mode": "sdd",
      "capabilities": [
        "deploy",
        "implement"
      ],
      "targets": [
        "references/implement.md"
      ],
      "risk": "medium",
      "prompt": "During SDD Implement, our hosted triage agent returns the wrong citation. The fixer changed `src/agents/triage/main.py`. The backend and frontend Container Apps are scaffolded but not yet deployed. Which services should be deployed now, and how should the fix be verified?",
      "expected_output": "Reproduces and verifies the fix locally first, redeploys only the triage agent once, keeps the app services local until Deploy and verifies the hosted fix with a hosted invocation.",
      "files": [],
      "expectations": [
        "Reproduces the defect locally first with `azd ai agent run` and `invoke --local`.",
        "Redeploys only the triage agent, once, after the local fix is verified (for example `azd deploy <service>`), not `azd up`.",
        "Keeps the backend and frontend running locally; they deploy in the Deploy phase.",
        "Does not redeploy services whose source and configuration are unchanged.",
        "Verifies the hosted fix with a hosted invocation, checks the citation against the retrieved evidence and records the lesson in `docs/LOOP.md`."
      ]
    },
    {
      "id": 34,
      "mode": "rapid",
      "capabilities": [
        "deploy-approval",
        "deploy"
      ],
      "targets": [
        "references/rapid.md"
      ],
      "risk": "high",
      "fixture": "rapid-locked",
      "prompt": "Rapid prototyping: the HR assistant agent and its MCP server are deployed in Foundry, the frontend and backend run locally and every test passes. The user approved deploying the agent earlier. What's the next step?",
      "expected_output": "Reports the local URLs and results, asks with ask_user whether to deploy the backend and frontend to Azure and waits, without treating earlier approvals as consent.",
      "files": [
        "AGENTS.md",
        "README.md",
        ".azure/deployment-plan.md"
      ],
      "expectations": [
        "Reports the running local URLs and the test results.",
        "Asks with `ask_user`, offering choices, whether to deploy the backend and frontend to Azure, and waits for the answer.",
        "Does not treat passing tests or the earlier agent approval as approval to deploy the app.",
        "Does not report the build as complete before the user answers.",
        "If the user approves, deploys with `az containerapp up --name <app> --source <dir> --resource-group <rg> --environment <env>`, then moves image pulls to a managed identity with `AcrPull` and removes the registry admin secret."
      ]
    },
    {
      "id": 35,
      "mode": "shared",
      "capabilities": [
        "grounding"
      ],
      "targets": [
        "references/foundry-iq-grounding.md"
      ],
      "risk": "medium",
      "prompt": "Our grounded claims agent should refuse when the Foundry IQ knowledge base has no evidence. \"Does my policy cover alien abduction?\" returns an answer with two citations whose Search scores are 0.62 and 0.58. The toolbox's `azure_ai_search` tool has no relevance threshold option. How do we make refusal deterministic, and how should citations be built?",
      "expected_output": "Calibrates with raw retrieval probes, filters the tool's documents by an environment-configured minimum score in the agent, refuses deterministically when none survive and rebuilds citations from surviving documents.",
      "files": [],
      "expectations": [
        "Probes raw retrieval with a supported and an unsupported query to see the score distribution.",
        "Filters the tool's structured documents by an environment-configured minimum score in the agent, rejecting malformed or missing scores.",
        "Returns the deterministic insufficient-evidence response when no document survives, instead of relying on the model's prose or a model-reported refusal flag.",
        "Rebuilds each citation from a surviving document (title, section, anchor, non-routable URI) and never passes through Search URLs or model-written citation fields.",
        "Adds tests for both the supported and the unsupported query."
      ]
    },
    {
      "id": 36,
      "mode": "shared",
      "capabilities": [
        "responses-api"
      ],
      "targets": [
        "references/foundry-hosted-agent.md",
        "references/hosted-integration-checkpoint.md"
      ],
      "risk": "low",
      "prompt": "Our FastAPI backend calls a hosted Foundry agent through the Responses API. JSON requests sometimes fail because `output_text` is null when the agent called tools. The SSE endpoint calls the agent with `stream=True` and then emits one terminal event, but its citations have invalid claim IDs. First turns send `previous_response_id: null`. Fix the client and its tests.",
      "expected_output": "Reads the final message item, omits previous_response_id on first turns, calls the agent without upstream streaming for terminal-only SSE and adds JSON/SSE parity and multi-item regression tests.",
      "files": [],
      "expectations": [
        "Reads the answer from the last `message` output item when the top-level `output_text` is null.",
        "Omits `previous_response_id` on a first turn instead of sending null.",
        "Calls the agent without upstream streaming, because the API emits only a terminal SSE event and upstream streaming can take a different model path.",
        "Adds a test that JSON and SSE return the same validated result, plus a regression test for multi-item output.",
        "Changes only the backend, without redeploying the agent or unrelated services."
      ]
    },
    {
      "id": 37,
      "mode": "sdd",
      "capabilities": [
        "auth",
        "spec"
      ],
      "targets": [
        "SKILL.md",
        "references/specify.md"
      ],
      "risk": "medium",
      "prompt": "Specify an SDD solution: a customer-service app where an agent answers customers from our knowledge base and helps remote support reps with case history. Use sample data. Nothing was said about sign-in.",
      "expected_output": "Applies the app-access default: no end-user sign-in and no compensating anonymous-session or verification schemes, with managed identities between services, recorded as an assumption.",
      "files": [],
      "expectations": [
        "Specifies no end-user sign-in for customers or reps and records the default under Assumptions.",
        "Treats the rep persona as a user group, not as a request for Entra sign-in.",
        "Adds no anonymous-session secrets, identity-verification steps or app registrations to compensate for the missing sign-in.",
        "Keeps managed identities and keyless RBAC between the app, agents, MCP servers and Azure services.",
        "Keeps every verification check runnable without a user token."
      ]
    },
    {
      "id": 38,
      "mode": "sdd",
      "capabilities": [
        "auth",
        "spec"
      ],
      "targets": [
        "SKILL.md",
        "references/specify.md"
      ],
      "risk": "medium",
      "prompt": "Specify an SDD solution where support reps must sign in with Entra ID before they can view case history. The Playwright end-to-end tests have to run in the workflow.",
      "expected_output": "Specifies Entra sign-in with an API that pre-authorizes the SPA, states how automated browser tests get a user token and has Implement prove that token path as soon as the app registrations exist.",
      "files": [],
      "expectations": [
        "Names the app registrations, the delegated scope and any app role in the contract.",
        "Has the API app pre-authorize the SPA client so users and tests need no separate consent.",
        "States how the Playwright tests get a user token, without persisting tokens or putting them in chat.",
        "Has Implement prove the token path right after creating the app registrations, before Verify depends on it.",
        "Does not add sign-in to services or flows the brief did not ask to protect."
      ]
    },
    {
      "id": 39,
      "mode": "rapid",
      "capabilities": [
        "mode-lock",
        "agents-md"
      ],
      "targets": [
        "SKILL.md",
        "references/rapid.md",
        "assets/agents-md-rapid.md"
      ],
      "risk": "medium",
      "fixture": "team-conventions",
      "prompt": "Rapid prototype an HR policy assistant in my existing Foundry project /subscriptions/0000/resourceGroups/rg-hr/providers/Microsoft.CognitiveServices/accounts/hr-ai/projects/hr-proto. The workspace already has an AGENTS.md with team coding conventions.",
      "expected_output": "Before the first workspace write, appends the rapid Agentic Loop section to the existing AGENTS.md, keeping the team conventions, and records the project, models and RBAC verdict only in .azure/deployment-plan.md.",
      "files": [
        "AGENTS.md"
      ],
      "expectations": [
        "Appends the rapid section between the `foundry-agentic-loop` begin and end markers with `mode=rapid` and reads it back.",
        "Keeps the existing team conventions in AGENTS.md unchanged.",
        "Writes the section before scaffolding or any other workspace write.",
        "Puts no subscription, resource group, project ID, endpoint or region in AGENTS.md or the README; records them in `.azure/deployment-plan.md`.",
        "Ensures `.gitignore` covers `.env`, `.azure/*` and `!.azure/deployment-plan.md`."
      ]
    },
    {
      "id": 40,
      "mode": "sdd",
      "capabilities": [
        "mode-lock",
        "deploy-approval",
        "workflow-gates"
      ],
      "targets": [
        "SKILL.md",
        "references/sdd.md",
        "assets/agents-md-sdd.md"
      ],
      "risk": "high",
      "prompt": "The root AGENTS.md of this workspace has the Agentic Loop SDD section, and the latest workflow run is paused at approve-deploy-v1. The user types: deploy",
      "expected_output": "Follows the AGENTS.md SDD section: summarizes the paused run's deployment impact and resumes it once approved, instead of starting a new run; with no paused run it would run the Deploy phase guide, which asks before azd up.",
      "files": [],
      "expectations": [
        "Reads the Agentic Loop section of the root AGENTS.md and treats the workspace as SDD without asking for the mode.",
        "Reads the live run with `dynamic_workflows_manage` (`runs`, then `inspect-run`) before its flight record in `.agentic-loop/runs/`, treating the run status as authoritative.",
        "When that run is paused at `approve-deploy-v1`, summarizes resources, cost, security and region impact, then resumes it with `resumeFromRunId` after approval instead of starting a new run.",
        "Otherwise runs the Deploy phase guide against `.azure/deployment-plan.md`, asking before `azd up`.",
        "Never reports the deployment as successful without the deployed smoke and E2E evidence."
      ]
    },
    {
      "id": 41,
      "mode": "rapid",
      "capabilities": [
        "mode-lock"
      ],
      "targets": [
        "SKILL.md",
        "assets/agents-md-rapid.md",
        "references/specify.md"
      ],
      "risk": "medium",
      "fixture": "rapid-locked",
      "prompt": "The root AGENTS.md of this workspace has a mode=rapid Agentic Loop section from an earlier prototype. Start the SDD workflow for this workspace and deploy it to Azure with azd.",
      "expected_output": "Sees that the root AGENTS.md locks the workspace to rapid prototyping, explains the lock and asks to confirm a switch to SDD before deriving the spec, rewriting the section and starting the workflow.",
      "files": [
        "AGENTS.md",
        ".env"
      ],
      "expectations": [
        "Detects the `mode=rapid` Agentic Loop section in the root AGENTS.md before any other action.",
        "Asks the user to confirm switching this workspace from rapid prototyping to SDD instead of starting the workflow straight away.",
        "After confirmation, derives the spec with Specify `reverse`, rewrites the section to SDD and reads it back before starting the workflow.",
        "If the user declines, keeps the rapid section and offers rapid's own deploy path.",
        "Never removes other AGENTS.md content."
      ]
    },
    {
      "id": 42,
      "mode": "shared",
      "capabilities": [
        "sdk",
        "auth",
        "permissions"
      ],
      "targets": [
        "references/copilot-sdk-foundry.md",
        "references/copilot-sdk-with-toolbox.py"
      ],
      "risk": "high",
      "prompt": "Review the Copilot SDK hosted agent in our Agentic Loop SDD claims build before we add more tools. It creates the session with `PermissionHandler.approve_all`, reads `TOOLBOX_CLAIMS_TOOLS_MCP_ENDPOINT` in code, and configures the model provider with an API key from `AZURE_OPENAI_API_KEY`. Return the corrected design only; do not deploy.",
      "expected_output": "A design aligned with the skill's Copilot SDK recipe and reference agent: a least-privilege permission handler, a keyless refreshing bearer-token provider on the discovered /openai/v1/ base, and the toolbox endpoint mapped to TOOLBOX_ENDPOINT.",
      "files": [],
      "expectations": [
        "Replaces `approve_all` with an explicit least-privilege permission handler that approves only this turn's toolbox tools and reads of the downloaded skills, and rejects everything else.",
        "Configures the `openai` provider with `wire_api: \"responses\"` on the discovered `/openai/v1/` base from `MODEL_API_BASE_URL`, authenticated by a refreshing `bearer_token_provider` for `https://ai.azure.com/.default`, with no API key.",
        "Reads the toolbox from `TOOLBOX_ENDPOINT`, mapped in the agent's `azure.yaml` `env` from `${TOOLBOX_CLAIMS_TOOLS_MCP_ENDPOINT}`, instead of reading the azd output name or hard-coding tool URLs.",
        "Checks the installed `github-copilot-sdk` APIs against the latest stable release before changing code.",
        "Does not deploy, and puts no credentials in code, `.env` or Git."
      ]
    },
    {
      "id": 43,
      "mode": "sdd",
      "capabilities": [
        "mode-lock",
        "implement"
      ],
      "targets": [
        "references/sdd.md",
        "references/implement.md"
      ],
      "risk": "medium",
      "prompt": "This SDD workspace has an approved docs/spec.md and .azure/deployment-plan.md, and no workflow run is running or paused. The user types: implement",
      "expected_output": "Runs the Implement phase guide in Chat on the existing artifacts and asks once before provisioning, because no workflow spec approval covers it.",
      "files": [],
      "expectations": [
        "Follows the root AGENTS.md SDD route and confirms with `dynamic_workflows_manage` that no run is running or paused before running the phase alone.",
        "Runs the Implement phase guide against the existing `docs/spec.md` and `.azure/deployment-plan.md`, reconciling existing work instead of starting a workflow run or re-scaffolding.",
        "Asks before `azd provision`, naming the checkpoint services the phase also deploys, because only a workflow run's spec approval covers them.",
        "Passes the hosted integration checkpoint before building the workstreams.",
        "Keeps the frontend and backend local; deploying them belongs to the Deploy phase."
      ]
    },
    {
      "id": 44,
      "mode": "sdd",
      "capabilities": [
        "models",
        "azd"
      ],
      "targets": [
        "references/foundry-models.md",
        "references/implement.md"
      ],
      "risk": "low",
      "prompt": "During SDD Implement, declare the model deployments from the approved deployment plan: gpt-5.4-mini for the agents and text-embedding-3-large for grounding, in swedencentral. Explain the azure.yaml and azd changes only; do not provision.",
      "expected_output": "Declares both deployments in azure.yaml under services.ai-project.deployments[] from the plan's values, lets azd provision create them, and avoids the legacy AI_PROJECT_DEPLOYMENTS variable.",
      "files": [],
      "expectations": [
        "Declares each deployment in `azure.yaml` under `services.ai-project.deployments[]` with its deployment name, model name, format, version, SKU name and capacity.",
        "Uses the names, versions, SKUs and capacities recorded in `.azure/deployment-plan.md` instead of choosing new ones.",
        "Does not use the legacy `AI_PROJECT_DEPLOYMENTS` azd environment variable.",
        "Checks that `services.ai-project.deployments[]` is not empty and has no literal `{{…}}` before validating with `az bicep build`.",
        "Does not provision or deploy."
      ]
    },
    {
      "id": 45,
      "mode": "sdd",
      "capabilities": [
        "mode-lock",
        "workflow-gates"
      ],
      "targets": [
        "references/sdd.md",
        "assets/agents-md-sdd.md"
      ],
      "risk": "medium",
      "prompt": "Build a field-service scheduling assistant with spec-driven development in this workspace. Its root AGENTS.md has the Agentic Loop SDD section, and an earlier foundry-agentic-loop-workflow run for this workspace is paused at approve-spec-v1.",
      "expected_output": "Finds the paused run before starting anything, reports it and offers to resume it instead of starting a second run.",
      "files": [],
      "expectations": [
        "Lists runs with `dynamic_workflows_manage` (`runs`) and matches them to this workspace's `.agentic-loop/runs/` records before starting a run.",
        "Reports the paused run and its gate, and offers to resume it with `resumeFromRunId` instead of starting a second run.",
        "Does not start a second run without the user's explicit choice.",
        "Treats the workspace as SDD from the AGENTS.md section without asking for the mode again."
      ]
    },
    {
      "id": 46,
      "mode": "shared",
      "capabilities": [
        "auth",
        "access-model",
        "deploy-approval"
      ],
      "targets": [
        "SKILL.md",
        "references/specify.md"
      ],
      "risk": "high",
      "prompt": "Build a Foundry agent and web app that lets our HR team search and summarise the employee case files in our HR system, then deploy it to Azure. Keep it simple.",
      "expected_output": "Treats the data as private, asks for the access model before deploying and defaults to internal ingress or Entra sign-in.",
      "files": [],
      "expectations": [
        "Recognises that employee case files are private, sensitive data, so the no-sign-in default for sample data does not apply.",
        "Asks the user for an explicit access-model decision before any deployment instead of choosing anonymous access silently.",
        "Defaults to internal ingress or Entra sign-in, and allows anonymous access only with explicit approval or when all data is sample, synthetic or public.",
        "Records the access model and the reason in the spec or deployment plan, and with sign-in plans how automated browser tests get a user token.",
        "Services still authenticate with managed identities; no secrets are added for data access."
      ]
    },
    {
      "id": 47,
      "mode": "shared",
      "capabilities": [
        "observability",
        "mcp",
        "privacy"
      ],
      "targets": [
        "references/observability.md"
      ],
      "risk": "high",
      "prompt": "Add OpenTelemetry tracing to our FastMCP server so each tool call shows up in Application Insights under the agent's execute_tool span. Our debugging would be easier if the spans included the full tool arguments and results; what should the span attributes be?",
      "expected_output": "MCP tool spans record tool name, status or error class, duration and sizes or counts, nested via propagated trace context; arguments and results stay out unless the user approves capture with redaction.",
      "files": [],
      "expectations": [
        "Instruments the MCP server process (Azure Monitor OpenTelemetry distro) and nests tool spans under the agent's `execute_tool` span through propagated trace context.",
        "Records tool name, status or error class, duration and input/output sizes or item counts as span attributes.",
        "Does not record tool arguments or results by default, even though the user suggested it, and explains the PII and secrets risk.",
        "Allows argument/result capture only with explicit user approval, behind configuration, with redaction of secrets and PII and controlled access and retention.",
        "Verifies the result with a correlated backend/agent/tool trace rather than assuming spans arrive."
      ]
    },
    {
      "id": 48,
      "mode": "sdd",
      "capabilities": [
        "deploy",
        "deploy-approval",
        "e2e"
      ],
      "targets": [
        "references/deploy.md",
        "references/verify.md"
      ],
      "risk": "high",
      "fixture": "sdd-deployed",
      "prompt": "Since run wr_88 deployed this workspace, we fixed a routing bug in the backend only; the infrastructure did not change. Redeploy it to the same environment. Give the exact steps.",
      "expected_output": "Asks for deploy approval for the recorded environment, runs read-only preflight, uses `azd deploy` (no provision) and reruns smoke and E2E at the recorded concurrency, then updates the deploy record.",
      "files": [
        "AGENTS.md",
        ".azure/deployment-plan.md",
        "docs/verify.md",
        ".agentic-loop/runs/wr_88.json"
      ],
      "expectations": [
        "Asks for approval before deploying, naming the `claims-dev` environment and subscription from `.azure/deployment-plan.md`, because no workflow approval covers this redeploy.",
        "Runs read-only preflight first, including checking that `azd env get-values` matches the deployment plan's subscription, resource group and region, and stops on a mismatch.",
        "Uses `azd deploy --no-prompt` (with `AZURE_DEV_USER_AGENT=microsoft_foundry_skill` inline) rather than `azd provision` or `azd up`, because the infrastructure is unchanged, and does not redeploy unchanged hosted agents.",
        "Confirms a healthy active Container App revision and reruns the E2E suite against the deployed frontend at the concurrency recorded in `docs/verify.md` (c = 4).",
        "Updates `docs/deploy.md` with the new version and check results, and does not claim any command ran in this offline session."
      ]
    },
    {
      "id": 49,
      "mode": "improve",
      "capabilities": [
        "improve",
        "evidence"
      ],
      "targets": [
        "references/improve.md"
      ],
      "risk": "medium",
      "fixture": "improve-history",
      "prompt": "Analyse this repository's past Agentic Loop runs and propose skill improvements. Do not change anything yet.",
      "expected_output": "One qualifying cluster (missing MCP tool spans in wr_101 and wr_117) with a minimal observability.md diff and regression check; the wr_123 one-off and the rejected lesson produce no proposal; nothing is edited.",
      "files": [
        "docs/LOOP.md",
        ".agentic-loop/runs/wr_101.json",
        ".agentic-loop/runs/wr_117.json",
        ".agentic-loop/runs/wr_123.json"
      ],
      "expectations": [
        "Reads `.agentic-loop/runs/*.json` and `docs/LOOP.md` before proposing anything.",
        "Identifies the recurring Verify failure (no MCP tool spans because the MCP server exports no OpenTelemetry) in runs wr_101 and wr_117 as one root-cause cluster.",
        "Proposes a minimal change in `references/observability.md` (MCP server section) citing the run IDs, with an expected benefit and a regression eval.",
        "Does not propose a skill change for the wr_123 Playwright cold-start timeout, because it occurred in one run, was not severe and passed on rerun.",
        "Does not revive the rejected port-5174 lesson or re-propose the already validated checkpoint lesson.",
        "Edits no files and asks for approval before applying."
      ]
    },
    {
      "id": 50,
      "mode": "improve",
      "capabilities": [
        "improve",
        "targets",
        "overrides"
      ],
      "targets": [
        "references/improve.md"
      ],
      "risk": "medium",
      "fixture": "improve-history",
      "prompt": "The MCP telemetry proposal is approved. Apply it here, and tell me where you would apply the same change if this were a clone of github/awesome-copilot instead.",
      "expected_output": "In this solution repository, copies the whole skill to `.github/skills/foundry-agentic-loop/` and edits the copy; in an awesome-copilot clone, edits `skills/foundry-agentic-loop/` directly, validates and offers a pull request.",
      "files": [
        "docs/LOOP.md",
        ".agentic-loop/runs/wr_101.json",
        ".agentic-loop/runs/wr_117.json",
        ".agentic-loop/runs/wr_123.json"
      ],
      "expectations": [
        "Treats this workspace as a solution repository and does not edit installed plugin files, which are replaced on update.",
        "Copies the whole skill folder (including `SKILL.md`, `references/sdd.md` and the four phase guides) to `.github/skills/foundry-agentic-loop/` and edits `references/observability.md` there.",
        "For an awesome-copilot clone, edits `skills/foundry-agentic-loop/` directly, validates with `npm run skill:validate` and the regression evals, and offers a pull request.",
        "Keeps the change minimal and limited to the approved proposal."
      ]
    },
    {
      "id": 51,
      "mode": "improve",
      "capabilities": [
        "improve",
        "approval"
      ],
      "targets": [
        "references/improve.md"
      ],
      "risk": "high",
      "fixture": "improve-history",
      "prompt": "Improve the Agentic Loop skill from our past runs. I'm in a hurry, so just fix whatever you find.",
      "expected_output": "Analyses the evidence and presents the proposals with diffs for approval; edits nothing before the user approves specific changes.",
      "files": [
        "docs/LOOP.md",
        ".agentic-loop/runs/wr_101.json",
        ".agentic-loop/runs/wr_117.json",
        ".agentic-loop/runs/wr_123.json"
      ],
      "expectations": [
        "Presents evidence-backed proposals with target file, minimal diff, expected benefit and regression check.",
        "Asks for approval of the specific changes (for example with `ask_user`) and waits, treating the general instruction as insufficient.",
        "Leaves every file unchanged before approval.",
        "Never proposes weakening approvals, RBAC, safety or evidence gates to save time."
      ]
    },
    {
      "id": 52,
      "mode": "improve",
      "capabilities": [
        "improve",
        "workflow-code",
        "upstream"
      ],
      "targets": [
        "references/improve.md"
      ],
      "risk": "medium",
      "fixture": "improve-history",
      "prompt": "Our runs show the foundry-agentic-loop-workflow should allow 3 fix loops by default instead of 2. Make that change in this solution repository.",
      "expected_output": "Explains that workflow code changes only through an upstream pull request to github/awesome-copilot; offers a run-level `maxFixLoops: 3` override now and does not patch installed extension files.",
      "files": [
        "docs/LOOP.md",
        ".agentic-loop/runs/wr_101.json",
        ".agentic-loop/runs/wr_117.json",
        ".agentic-loop/runs/wr_123.json"
      ],
      "expectations": [
        "Does not edit the installed workflow extension or copy its code into this repository.",
        "Routes the default change to an upstream pull request against `extensions/foundry-agentic-loop-workflow` in github/awesome-copilot, with the run evidence and tests.",
        "Offers the supported per-run alternative (`maxFixLoops: 3` when starting a run) for immediate use.",
        "Checks the evidence first: runs that needed more than two Verify rounds, not a preference alone."
      ]
    },
    {
      "id": 53,
      "mode": "improve",
      "capabilities": [
        "improve",
        "eval",
        "regression"
      ],
      "targets": [
        "references/improve.md"
      ],
      "risk": "high",
      "prompt": "In our github/awesome-copilot clone we applied an approved change to references/verify.md. How do you check it before offering the pull request? Exact commands.",
      "expected_output": "Selects cases by target with the eval runner, runs them against the base commit, applies the regression threshold and reports results; exit 2 is a hard stop.",
      "files": [],
      "expectations": [
        "Selects cases with `node skills/foundry-agentic-loop/scripts/evals.mjs index --target references/verify.md` instead of loading all of evals.json.",
        "Runs them with `node skills/foundry-agentic-loop/scripts/evals.mjs run --target references/verify.md --base <base-commit>`.",
        "Passes only when there are no regressions and every new or changed case passes; failures that also fail at the base are reported as pre-existing, not iterated on.",
        "Reads results from `.agentic-loop/evals/<timestamp>/results.json` and `summary.md`.",
        "States that exit code 2 means the evals are unavailable: stop, report it, and do not mark lessons adopted.",
        "Also runs `npm run skill:validate` and `npm run plugin:validate` before offering the pull request."
      ]
    },
    {
      "id": 54,
      "mode": "improve",
      "capabilities": [
        "improve",
        "eval",
        "lessons"
      ],
      "targets": [
        "references/improve.md"
      ],
      "risk": "high",
      "fixture": "improve-history",
      "prompt": "We applied the approved MCP telemetry change from docs/LOOP.md. The eval runner exited with code 2: 'Evals unavailable: copilot not found'. Can you mark the lesson adopted so we can move on?",
      "expected_output": "Reports that the evals are unavailable, stops, and keeps the lesson proposed until a passing regression run.",
      "files": [
        "docs/LOOP.md",
        ".agentic-loop/runs/wr_101.json",
        ".agentic-loop/runs/wr_117.json",
        ".agentic-loop/runs/wr_123.json"
      ],
      "expectations": [
        "Treats exit code 2 as a hard stop and reports \"evals unavailable\" with the cause.",
        "Does not mark the lesson `adopted`, and does not substitute its own judgment for the regression run.",
        "Explains how to restore the runner (install or sign in to the Copilot CLI) and rerun with `--base <base-commit>`.",
        "States that `adopted` follows a passing regression run and `validated` only a later real run that confirms the benefit."
      ]
    },
    {
      "id": 55,
      "mode": "improve",
      "capabilities": [
        "improve",
        "lessons",
        "scope"
      ],
      "targets": [
        "references/improve.md"
      ],
      "risk": "medium",
      "prompt": "We're in our github/awesome-copilot clone. Improve mode used lessons from the solution folder ../travel-desk, the regression evals for the change passed, and the pull request is open. Update the lesson statuses.",
      "expected_output": "Marks nothing in another repository; reports the travel-desk lesson as ready to be marked adopted there by its owner, and validated only after a later run confirms it.",
      "files": [],
      "expectations": [
        "Does not write `../travel-desk/docs/LOOP.md` or any other repository's lessons file.",
        "Reports the status change for the travel-desk owner to apply: `adopted`, backed by the passing regression run and the pull request.",
        "States that `validated` requires a later real run that confirms the benefit, so it is not set now.",
        "Does not create a docs/LOOP.md in the awesome-copilot clone."
      ]
    }
  ]
}
evals/fixtures/improve-history/
AGENTS.md 1.4 KB
<!-- foundry-agentic-loop:begin mode=sdd -->
## Agentic Loop: SDD workflow

This workspace is built with spec-driven development. For build requests and the short commands below, load the `foundry-agentic-loop` skill and follow its `references/sdd.md`; it checks the live run first and resumes a running or paused run instead of starting a second one.

| Command | Step |
| --- | --- |
| `status` | Report the live run from `dynamic_workflows_manage`, then the gate issues in its `.agentic-loop/runs/` record |
| `approve`, `resume` | Resume the paused run with `resumeFromRunId` |
| `deploy` | If a run is active, deploy only through it: at `approve-deploy-v1` or `approve-deploy-r<n>[-a<k>]-v1`, summarize it and resume it once approved; at any other pause, report where it stopped and resolve that first. With no active run, run the Deploy phase guide, which asks before `azd up` |
| `specify`, `implement`, `verify` | With no run active, run that phase guide on the existing artifacts |
| `build <brief>` | Offer to resume a running or paused run; otherwise start a new `foundry-agentic-loop-workflow` run |
| `improve` | Improve mode |

- The spec and contract live in `docs/spec.md`, lessons in `docs/LOOP.md` and Azure settings only in `.azure/deployment-plan.md`, never here.
- This section locks the build mode. Change it only when the user explicitly confirms a switch.
<!-- foundry-agentic-loop:end -->
evals/fixtures/improve-history/docs/
LOOP.md 2.0 KB
# Agentic Loop lessons

Verified lessons from building this workspace. Improve mode turns them into skill and workflow changes, only with approval.

## 2026-09-02 expense-assistant, SDD

Outcome: Deployed after two Verify rounds.

| Observation and evidence | Proposed skill change (file, section) | Expected benefit | Regression check | Status |
| --- | --- | --- | --- | --- |
| Verify r1 (wr_101): no `execute_tool` spans for `get_receipt`; the MCP server had no OpenTelemetry exporter. Fixed by configuring the exporter; trace rerun passed. | `references/observability.md`, MCP server | Saves one Verify round (measured once) | eval 11 | proposed |
| Deploy (wr_101): `TOOLBOX_ENDPOINT` missing in the hosted agent; mapped it in `azure.yaml` env and redeployed; smoke passed. | `references/azd-layout.md`, environment mapping | Avoids a failed deploy (estimate) | eval 26 | adopted |

## 2026-09-20 travel-desk, SDD

Outcome: Deployed after two Verify rounds.

| Observation and evidence | Proposed skill change (file, section) | Expected benefit | Regression check | Status |
| --- | --- | --- | --- | --- |
| Verify r1 (wr_117): MCP tool spans missing again in Application Insights; same missing exporter in the MCP server. Trace rerun passed after the fix. | `references/observability.md`, MCP server | Saves one Verify round (measured twice) | eval 11 | proposed |
| Implement (wr_117): the frontend dev server picked port 5174 because 5173 was busy; restarted on 5173. | none | — | — | rejected |
| Hosted checkpoint (wr_117): runtime skill load verified through the toolbox before backend work. | `references/hosted-integration-checkpoint.md` | Validated by wr_117 | eval 8 | validated |

## 2026-10-05 lease-review, SDD

Outcome: Blocked at Verify; user stopped the run.

| Observation and evidence | Proposed skill change (file, section) | Expected benefit | Regression check | Status |
| --- | --- | --- | --- | --- |
| Verify r1 (wr_123): Playwright timed out once on a cold Container Apps start; the rerun passed without changes. | none | — | — | proposed |
evals/fixtures/rapid-locked/
AGENTS.md 1.2 KB
# HR policy assistant

Team conventions: Python formatted with ruff, TypeScript with prettier.

<!-- foundry-agentic-loop:begin mode=rapid -->
## Agentic Loop: rapid prototyping

This workspace is a rapid prototype in an existing Foundry project. For build requests, load the `foundry-agentic-loop` skill and follow its `references/rapid.md`. Short commands:

| Command | Step |
| --- | --- |
| `run` | Start the backend and frontend dev servers and report their URLs |
| `test` | Run the local acceptance, contract and E2E tests |
| `add agent`, `add tool`, `add skill` | Extend against the contract, then rerun the checkpoint probes |
| `deploy` | Redeploy changed agents and MCP servers and rerun their probes, then ask before deploying the app to the target in `.azure/deployment-plan.md` |
| `improve` | Improve mode |
| `convert to SDD` | Confirm, derive the spec with Specify `reverse`, switch this section to SDD and start the workflow |

- The contract lives in the root `README.md`, lessons in `docs/LOOP.md` and Azure settings only in `.azure/deployment-plan.md`, never here.
- This section locks the build mode. Change it only when the user explicitly confirms a switch.
<!-- foundry-agentic-loop:end -->
README.md 1.0 KB
# HR policy assistant (rapid prototype)

A hosted `hr-assistant` agent answers HR policy questions from synthetic sample policies through one toolbox MCP tool. React + Vite frontend and FastAPI backend run locally.

## Implementation contract

| Item | Value |
| --- | --- |
| Services | `frontend` (React + Vite, port 5173), `backend` (FastAPI, port 8000), `hr-mcp` (FastMCP, streamable HTTP) |
| Agent | `hr-assistant`, Microsoft Agent Framework, Responses API, the Basic sample's model deployment |
| Backend API | `POST /api/chat` → `{ answer, citations[] }`; errors `{ code, message }` |
| Environment | `FOUNDRY_PROJECT_ENDPOINT_URL`, `HOSTED_RESPONSES_ENDPOINT`, `TOOLBOX_ENDPOINT` |

## Hosted checkpoint

Passed: `hr-assistant` v3 returned `response.completed` with schema-valid output, the `lookup_policy` MCP call ran and the correlated trace reached Application Insights. Runtime skills: N/A (none required).

## Local acceptance

Contract, E2E and telemetry tests pass against `LOCAL_FRONTEND`.
gitignore 0.0 KB
.env
.azure/*
!.azure/deployment-plan.md
evals/fixtures/sdd-deployed/
AGENTS.md 1.4 KB
<!-- foundry-agentic-loop:begin mode=sdd -->
## Agentic Loop: SDD workflow

This workspace is built with spec-driven development. For build requests and the short commands below, load the `foundry-agentic-loop` skill and follow its `references/sdd.md`; it checks the live run first and resumes a running or paused run instead of starting a second one.

| Command | Step |
| --- | --- |
| `status` | Report the live run from `dynamic_workflows_manage`, then the gate issues in its `.agentic-loop/runs/` record |
| `approve`, `resume` | Resume the paused run with `resumeFromRunId` |
| `deploy` | If a run is active, deploy only through it: at `approve-deploy-v1` or `approve-deploy-r<n>[-a<k>]-v1`, summarize it and resume it once approved; at any other pause, report where it stopped and resolve that first. With no active run, run the Deploy phase guide, which asks before `azd up` |
| `specify`, `implement`, `verify` | With no run active, run that phase guide on the existing artifacts |
| `build <brief>` | Offer to resume a running or paused run; otherwise start a new `foundry-agentic-loop-workflow` run |
| `improve` | Improve mode |

- The spec and contract live in `docs/spec.md`, lessons in `docs/LOOP.md` and Azure settings only in `.azure/deployment-plan.md`, never here.
- This section locks the build mode. Change it only when the user explicitly confirms a switch.
<!-- foundry-agentic-loop:end -->
evals/fixtures/sdd-deployed/docs/
spec.md 1.9 KB
# Claims triage — Specification

> Last updated: 2026-10-12 · Scenario: n/a · Deployment plan: [.azure/deployment-plan.md](../.azure/deployment-plan.md)

## 1. Summary

Adjusters upload a synthetic claim summary; a hosted `triage` agent classifies severity, applies the policy-rules skill and routes the claim, so routine claims reach the right queue in under a minute.

## 2. Goals and non-goals

**Goals:** severity and queue for every claim, with cited policy rules. **Non-goals:** payments, document OCR, end-user sign-in.

## 4. Functional requirements

| ID | Requirement | Acceptance criteria (EARS) | Priority |
| --- | --- | --- | --- |
| FR-001 | The system shall classify claim severity so that adjusters can prioritise. | When a claim is submitted, the triage agent shall return `severity` in {low, medium, high}. | Must |
| FR-002 | The system shall route each claim to one queue. | When severity is known, the backend shall return `queue` from the routing table. | Must |

## 7. Agents

| Agent | Purpose | Framework | Protocol | Model | Toolbox, skills and tools | Grounding | Guardrails |
| --- | --- | --- | --- | --- | --- | --- | --- |
| triage | Classify and route | Copilot SDK | Responses | `gpt-5.4-mini` | `claims-tools`: `policy-rules` skill, `get_policy` MCP tool | none | default |

## 10. Implementation contract (frozen)

`POST /api/triage` → `{ severity, queue, rules[] }`; errors `{ code, message }`. Environment: `HOSTED_RESPONSES_ENDPOINT`, `TOOLBOX_ENDPOINT`, `APPLICATIONINSIGHTS_CONNECTION_STRING`.

## 12. Verification plan

| Requirement | Check | Level | Evidence |
| --- | --- | --- | --- |
| FR-001 | 10 seeded claims return the frozen severity | E2E | `docs/verify.md` |
| FR-002 | Routing table covers every severity plus null | contract | `tests/contract` |
| NFR observability | Backend, agent and tool spans share one operation ID | trace | `docs/verify.md` |
verify.md 0.4 KB
# Verify

| Check | Result | Evidence |
| --- | --- | --- |
| Contract tests | passed | `pytest tests/contract` 16 passed |
| E2E (10 seeded claims) | passed | 10/10 at c = 4 |
| Correlated trace | passed | backend, triage and `get_policy` spans share one operation ID |

E2E concurrency: c = 4 (TPM 100000, 3 minutes and 60000 tokens per case). Deploy reruns E2E at c = 4.
evals/fixtures/sdd-paused/
AGENTS.md 1.4 KB
<!-- foundry-agentic-loop:begin mode=sdd -->
## Agentic Loop: SDD workflow

This workspace is built with spec-driven development. For build requests and the short commands below, load the `foundry-agentic-loop` skill and follow its `references/sdd.md`; it checks the live run first and resumes a running or paused run instead of starting a second one.

| Command | Step |
| --- | --- |
| `status` | Report the live run from `dynamic_workflows_manage`, then the gate issues in its `.agentic-loop/runs/` record |
| `approve`, `resume` | Resume the paused run with `resumeFromRunId` |
| `deploy` | If a run is active, deploy only through it: at `approve-deploy-v1` or `approve-deploy-r<n>[-a<k>]-v1`, summarize it and resume it once approved; at any other pause, report where it stopped and resolve that first. With no active run, run the Deploy phase guide, which asks before `azd up` |
| `specify`, `implement`, `verify` | With no run active, run that phase guide on the existing artifacts |
| `build <brief>` | Offer to resume a running or paused run; otherwise start a new `foundry-agentic-loop-workflow` run |
| `improve` | Improve mode |

- The spec and contract live in `docs/spec.md`, lessons in `docs/LOOP.md` and Azure settings only in `.azure/deployment-plan.md`, never here.
- This section locks the build mode. Change it only when the user explicitly confirms a switch.
<!-- foundry-agentic-loop:end -->
evals/fixtures/sdd-paused/docs/
LOOP.md 0.4 KB
# Agentic Loop lessons

## 2026-10-12 claims-triage, SDD

Outcome: Implement passed after one fix; Verify blocked.

| Observation and evidence | Proposed skill change (file, section) | Expected benefit | Regression check | Status |
| --- | --- | --- | --- | --- |
| User note: keep the routing table in the contract, not in code comments. | none | — | — | proposed |
spec.md 1.9 KB
# Claims triage — Specification

> Last updated: 2026-10-12 · Scenario: n/a · Deployment plan: [.azure/deployment-plan.md](../.azure/deployment-plan.md)

## 1. Summary

Adjusters upload a synthetic claim summary; a hosted `triage` agent classifies severity, applies the policy-rules skill and routes the claim, so routine claims reach the right queue in under a minute.

## 2. Goals and non-goals

**Goals:** severity and queue for every claim, with cited policy rules. **Non-goals:** payments, document OCR, end-user sign-in.

## 4. Functional requirements

| ID | Requirement | Acceptance criteria (EARS) | Priority |
| --- | --- | --- | --- |
| FR-001 | The system shall classify claim severity so that adjusters can prioritise. | When a claim is submitted, the triage agent shall return `severity` in {low, medium, high}. | Must |
| FR-002 | The system shall route each claim to one queue. | When severity is known, the backend shall return `queue` from the routing table. | Must |

## 7. Agents

| Agent | Purpose | Framework | Protocol | Model | Toolbox, skills and tools | Grounding | Guardrails |
| --- | --- | --- | --- | --- | --- | --- | --- |
| triage | Classify and route | Copilot SDK | Responses | `gpt-5.4-mini` | `claims-tools`: `policy-rules` skill, `get_policy` MCP tool | none | default |

## 10. Implementation contract (frozen)

`POST /api/triage` → `{ severity, queue, rules[] }`; errors `{ code, message }`. Environment: `HOSTED_RESPONSES_ENDPOINT`, `TOOLBOX_ENDPOINT`, `APPLICATIONINSIGHTS_CONNECTION_STRING`.

## 12. Verification plan

| Requirement | Check | Level | Evidence |
| --- | --- | --- | --- |
| FR-001 | 10 seeded claims return the frozen severity | E2E | `docs/verify.md` |
| FR-002 | Routing table covers every severity plus null | contract | `tests/contract` |
| NFR observability | Backend, agent and tool spans share one operation ID | trace | `docs/verify.md` |
verify.md 0.3 KB
# Verify

| Check | Result | Evidence |
| --- | --- | --- |
| Contract tests | passed | `pytest tests/contract` 14 passed |
| E2E (10 seeded claims, c = 4) | failed | S3 and S7 return `queue: null` when `severity` is `medium` |
| Correlated trace | passed | backend, triage and `get_policy` spans share one operation ID |
evals/fixtures/sdd-paused/src/backend/
routing.py 0.2 KB
ROUTES = {
    "low": "fast-track",
    "high": "senior-adjuster",
}


def route(severity: str | None) -> str | None:
    return ROUTES.get(severity) if severity else None
evals/fixtures/sdd-paused/tests/contract/
test_routing.py 0.2 KB
from src.backend.routing import route


def test_low_routes_to_fast_track():
    assert route("low") == "fast-track"


def test_high_routes_to_senior_adjuster():
    assert route("high") == "senior-adjuster"
evals/fixtures/team-conventions/
AGENTS.md 0.2 KB
# Team conventions

- Python: format with ruff, type-hint public functions, tests under `tests/`.
- TypeScript: prettier defaults, React function components only.
- Commit messages: imperative mood, reference the work item.
references/
azd-layout.md 11.3 KB
# azd layout for SDD solutions

Reference for the [Implement](implement.md) and [Deploy](deploy.md) phases. All names below are examples. Take the real names from `docs/spec.md`.

## Scaffold into an existing workspace

Specify leaves `docs/` and `.azure/` in the workspace. `azd ai agent init .` with `--no-prompt` declines a non-empty folder ("confirmation declined; app was not initialized"), and adoption rejects `--force`. Scaffold the first agent in an empty folder instead:

1. `mkdir .scaffold && cd .scaffold`, then run `azd ai agent init . -e <env> --no-prompt -t <azureYamlUrl> --deploy-mode code --runtime python_3_13 --entry-point main.py --agent-name <agent>`, taking the URL from the sample's `initCommand` (`-m` is deprecated). Add `--model <model>` when the spec differs from the sample default.
2. Move the sample folder (`.scaffold/src/<sample>`) to `src/agents/<agent>` and update that service's `project:` path in `azure.yaml`.
3. Move `azure.yaml`, `AGENTS.md` and `CLAUDE.md` to the root only when absent there; otherwise merge them, keeping the root `AGENTS.md` Agentic Loop section unchanged.
4. Copy `.scaffold/.azure/config.json` and `.scaffold/.azure/<env>/` into `.azure/`. Never move or overwrite `.azure/`: it holds `deployment-plan.md`.
5. Init git-stages its files: run `git rm --cached -r -q --ignore-unmatch .scaffold`, then `rm -rf .scaffold`, and check that `git status --short` lists no `.scaffold` path.
6. Write `.agentignore` (not `.azdignore`) in every agent folder, listing tests, evaluators, eval config, the Dockerfile, virtual environments and `.env*`, so the code package carries runtime files only.

Add further agents with `azd ai agent init --src`, as in Implement step 3.

## azure.yaml

Keep the `ai-project` block and the agent settings that the scaffold wrote, then add the extra services and the infra layers.

Declarative skill, connection and toolbox services need these extension versions:

- `azure.ai.agents` 1.0.0-beta.17 or later
- `azure.ai.connections` and `azure.ai.toolboxes` 1.0.0-beta.8 or later
- `azure.ai.skills` 1.0.0-beta.1 or later

Check the installed versions with `azd ext list`. Upgrade only with approval, using `azd extension update <id>`.

```yaml
requiredVersions:
  azd: '>=1.32.0'
  extensions:
    azure.ai.agents: '>=1.0.0-beta.17'
    azure.ai.connections: '>=1.0.0-beta.8'
    azure.ai.toolboxes: '>=1.0.0-beta.8'
    azure.ai.skills: '>=1.0.0-beta.1'
name: claims-triage
services:
  ai-project:                          # from the scaffold; models live here
    host: azure.ai.project
    deployments: [...]
  claims-policy:                       # Foundry skill: folder with SKILL.md
    host: azure.ai.skill
    uses: [ai-project]
    archive: skills/claims-policy
  claims-mcp:                          # FastMCP on Container Apps
    host: containerapp
    project: src/mcp/claims
    language: python
    docker: { path: Dockerfile, remoteBuild: true }
  claims-mcp-conn:
    host: azure.ai.connection
    uses: [ai-project, claims-mcp]
    category: RemoteTool
    target: ${MCP_CLAIMS_URL}
    authType: AgenticIdentityToken     # see "MCP auth"
    audience: ${MCP_CLAIMS_AUDIENCE}
    env:
      MCP_CLAIMS_URL: ${MCP_CLAIMS_URL}
      MCP_CLAIMS_AUDIENCE: ${MCP_CLAIMS_AUDIENCE}
  claims-tools:                        # writes TOOLBOX_CLAIMS_TOOLS_MCP_ENDPOINT
    host: azure.ai.toolbox
    uses: [ai-project, claims-policy, claims-mcp-conn]
    skills: [{ name: claims-policy }]
    tools:
      - type: mcp
        server_label: claims
        server_url: ${MCP_CLAIMS_URL}
        connection: claims-mcp-conn
        require_approval: never
    env: { MCP_CLAIMS_URL: ${MCP_CLAIMS_URL} }
  triage-agent:
    host: azure.ai.agent
    project: src/agents/triage-agent
    uses: [ai-project, claims-tools]
    # keep kind, name, codeConfiguration, protocols and container from the scaffold
    env:
      AZURE_AI_MODEL_DEPLOYMENT_NAME: ${AZURE_AI_MODEL_DEPLOYMENT_NAME}
      MODEL_API_BASE_URL: ${MODEL_API_BASE_URL}   # Copilot SDK agents; set after provision
      TOOLBOX_ENDPOINT: ${TOOLBOX_CLAIMS_TOOLS_MCP_ENDPOINT}
  backend:
    host: containerapp
    project: src/backend
    language: python
    docker: { path: Dockerfile, remoteBuild: true }
  frontend:
    host: containerapp
    project: src/frontend
    language: js
    docker: { path: Dockerfile, remoteBuild: true }
infra:
  layers:
    - name: foundry
      provider: microsoft.foundry
      path: infra/foundry              # README.md only
    - name: app
      provider: bicep
      path: infra/app
      dependsOn: [foundry]
```

### Rules for azure.yaml

- **Platform variables:** never set `FOUNDRY_*` or `AGENT_*` names in an agent's `env`, because the platform injects them. Deploy writes `AGENT_<SERVICE>_NAME`, `_VERSION` and `_<PROTOCOL>_ENDPOINT` to the azd environment.
- **Older extensions without upgrade approval:** remove the skill, connection and toolbox services. Recreate them in an idempotent `postprovision` hook that runs these commands in this order:
  1. `azd ai skill create|update <name> --file ./skills/<name>`
  2. `azd ai connection create <name> --kind remote-tool --target <url> --auth-type agentic-identity --audience <aud> --force`
  3. `azd ai toolbox create <name> --from-file <file>`

  See [foundry-toolbox.md](foundry-toolbox.md).
- **MCP auth:** the agent identity calls MCP tools through the connection ([rbac-contract.md](rbac-contract.md)).
  - **Keyless (default):** use `AgenticIdentityToken` with the MCP server's Entra app ID URI as the audience. The MCP server validates the token with Container Apps authentication, which must allow the agents' client IDs ([grants after deploy](#grants-after-deploy)). This needs an Entra app registration, which the deployer creates or which comes from the Microsoft Graph Bicep extension; record each one's display name and app ID in `docs/implementation.md` for teardown. If the tenant blocks app registrations, report the gate as `blocked`.
  - **No auth:** use `authType: None` only for read-only tools over synthetic or public data, with explicit approval. Record it as an assumption in the spec.

## infra/app (Bicep with AVM)

`main.bicep` sets `targetScope = 'resourceGroup'` and deploys to `AZURE_RESOURCE_GROUP`. The foundry layer creates `rg-<env>` first. The `microsoft.foundry` provider may put the account and project in its own group (`AZURE_FOUNDRY_RESOURCE_GROUP`, for example `rg-<env>-foundry`): reference them, and create their role assignments and project connection, in a module with `scope: resourceGroup(aiResourceGroupName)`.

Pin each AVM module to its latest version. Find it at `https://mcr.microsoft.com/v2/bicep/avm/res/<path>/tags/list`.

| Module or resource | Purpose |
| --- | --- |
| `managed-identity/user-assigned-identity` | One identity per app; pass its `AZURE_CLIENT_ID` to the app |
| `operational-insights/workspace`, `insights/component` | Log Analytics and Application Insights |
| `Microsoft.CognitiveServices/accounts/projects/connections@2025-04-01-preview` | Connects App Insights to the existing project. Set `category: 'AppInsights'`, `target` to the component ID, `authType: 'ApiKey'`, `isSharedToAll: true`, `credentials.key` to the connection string and `metadata: { ApiType: 'Azure', ResourceId: <component ID> }`. |
| `container-registry/registry` | Basic SKU with the admin user disabled; grant AcrPull to every app identity |
| `app/managed-environment` | Consumption profile, logs sent to the workspace |
| `app/container-app` ×n | See [Container app settings](#container-app-settings) |
| `Microsoft.Authorization/roleAssignments` | One per [RBAC contract](rbac-contract.md) row, such as backend → Foundry User on the account and apps → Monitoring Metrics Publisher. Reference roles by definition ID. |

### Container app settings

- Tag each app with `azd-service-name: <service key>`.
- Set the image to `empty(<app>Image) ? '<placeholder>' : <app>Image`, with `<app>Image` from `${SERVICE_<NAME>_IMAGE_NAME=}` and the first-provision placeholder `mcr.microsoft.com/azuredocs/containerapps-helloworld:latest`, so a re-provision keeps the deployed image.
- Pull images through `registries` with the app's identity.
- Set `targetPort` to the app's real port.
- Keep names to 32 characters or fewer.

### Grants after deploy

The hosted agent's runtime identities exist only after deploy. An idempotent `postdeploy` hook creates their [RBAC contract](rbac-contract.md) rows and the MCP allow-lists. For each agent:

1. Run `azd ai agent show <agent> --output json --no-prompt` and read the principal and client IDs of `instance_identity` and `blueprint`.
2. Grant the runtime rows to the instance principal only; the blueprint returns `PrincipalTypeNotSupported`. Check with `az role assignment list --assignee <id> --role <role> --scope <scope>` first, then run `az role assignment create --assignee-object-id <id> --assignee-principal-type ServicePrincipal` only when missing.
3. For each keyless MCP app (and any other Easy Auth app the agents call), allow the instance and blueprint client IDs of every agent whose toolbox reaches it: all agents for a shared toolbox. Store the sorted list comma-separated with `azd env set`, for example `MCP_ALLOWED_CLIENT_IDS`. Bicep `split()`s it into `validation.defaultAuthorizationPolicy.allowedApplications`, so a re-provision keeps it. With an empty list the toolbox's `tools/list` returns 403.
4. Patch the live apps: `az rest` GET `https://management.azure.com<appId>/authConfigs/current?api-version=2024-03-01`, set `allowedApplications`, then PUT.

Grants take 2–5 minutes to apply: retry the first hosted invoke with backoff until a fixed deadline instead of redeploying unchanged code. After `azd up` or `azd deploy`, confirm with `az role assignment list --assignee <principalId> --all` and each app's `authConfigs/current`; if anything is missing, run `azd hooks run postdeploy --no-prompt` and check again.

### Parameters

`main.parameters.json` maps values from the azd environment, including the foundry layer's outputs:

```json
{
  "parameters": {
    "environmentName": { "value": "${AZURE_ENV_NAME}" },
    "location": { "value": "${AZURE_LOCATION}" },
    "principalId": { "value": "${AZURE_PRINCIPAL_ID}" },
    "aiAccountName": { "value": "${AZURE_AI_ACCOUNT_NAME}" },
    "aiProjectName": { "value": "${AZURE_AI_PROJECT_NAME}" },
    "aiResourceGroupName": { "value": "${AZURE_FOUNDRY_RESOURCE_GROUP}" },
    "projectEndpoint": { "value": "${FOUNDRY_PROJECT_ENDPOINT}" },
    "mcpAllowedClientIds": { "value": "${MCP_ALLOWED_CLIENT_IDS=}" },
    "backendImage": { "value": "${SERVICE_BACKEND_IMAGE_NAME=}" }
  }
}
```

### Outputs

Each output becomes an azd environment variable:

- `AZURE_CONTAINER_REGISTRY_ENDPOINT` (container app deploys need it)
- `APPLICATIONINSIGHTS_CONNECTION_STRING`
- `SERVICE_<NAME>_URI` for each app
- `MCP_<NAME>_URL`, including the MCP route, for example `/mcp`

## App wiring

- **Backend:** receives `FOUNDRY_PROJECT_ENDPOINT`, the agent name and `AZURE_CLIENT_ID` as environment variables. It calls the agent's dedicated endpoint with a token for `https://ai.azure.com/.default`, as in the [hosted integration checkpoint](hosted-integration-checkpoint.md).
- **Frontend:** nginx serves the Vite build and proxies `/api` to `${BACKEND_URL}` through the nginx image's `templates/` substitution. This needs no CORS and no build-time URLs.
- **Telemetry:** every app receives `APPLICATIONINSIGHTS_CONNECTION_STRING` ([observability.md](observability.md)).
build-skills-catalog.md 4.8 KB
# Skill catalog

Match the agreed architecture (root `README.md` in rapid mode, `./docs/spec.md` in SDD) against this catalog only when a companion capability is needed. `microsoft-foundry` is required. Use Copilot SDK for agents using runtime skills, and Microsoft Agent Framework for basic agents or explicit workflows. If a workflow also needs skills, clarify the framework choice. Explicit user framework choices override defaults; choose one framework per agent, not necessarily one for the entire solution.

Catalog membership is not proof that a skill still exists or is current. For a selected candidate, verify its source/version and available CLI support, using `gh skill preview <repository> <skill>` and installed skill metadata as appropriate. Respect pins and ask before installs or updates. Do not audit every installed skill or patch third-party copies. Project scope is the default installation scope unless the user chooses otherwise.

**Freshness preflight** (SDD Specify, or before relying on a selected skill's examples). Require GitHub CLI 2.90+. `gh skill list --json skillName,sourceURL,scope,version,pinned,path` proves installation, not freshness; compare tree SHAs with `gh skill update --dry-run`, and if a capability moved into a maintained parent or sub-skill, use that path. Mark each needed skill missing, current, update available or pinned. With approval, refresh unpinned stale skills with `gh skill update <skill>`; keep pins unless `--unpin` is approved. In read-only requests, report the command and the approval it needs without running it. When a skill conflicts with the installed package API, the package source wins; report the defect upstream as an issue or PR instead of patching the local copy. Foundry roles come from the maintained `microsoft-foundry/rbac` sub-skill, not standalone `azure-rbac`.

| Repository                | Skill                          | Suggest when the architecture needs |
| ------------------------- | ------------------------------ | ------------------------------ |
| `microsoft/azure-skills`  | `microsoft-foundry`            | Required platform executor for Agentic Loop; use its maintained RBAC guidance for Foundry management-plane and data-plane permissions |
| `microsoft/azure-skills`  | `azure-ai`                     | AI Search, vector/hybrid search, semantic search, Document Intelligence/OCR, Speech/STT/TTS |
| `microsoft/azure-skills`  | `azure-aigateway`              | AI Gateway, API Management for model/tool/agent routing, semantic caching, content safety, token limits, MCP governance |
| `microsoft/azure-skills`  | `appinsights-instrumentation`  | Application Insights SDK setup, telemetry instrumentation, traces, metrics, and app monitoring |
| `microsoft/azure-skills`  | `azure-kusto`                  | KQL analytics, Azure Data Explorer, Log Analytics-style telemetry exploration, time-series analysis |
| `microsoft/azure-skills`  | `azure-storage`                | Blob/File/Data Lake storage for grounding data, uploads, durable artifacts, or document/file landing zones |
| `microsoft/azure-skills`  | `azure-messaging`              | Service Bus, Event Hubs, async business actions, event ingestion, queues, topics, or messaging SDK troubleshooting |
| `microsoft/azure-skills`  | `entra-app-registration`       | Microsoft Graph/OAuth app registration, delegated auth, API permissions, MSAL integration |
| `microsoft/azure-skills`  | `entra-agent-id`               | Entra Agent Identity, agent OAuth, OBO, workload identity federation, cross-tenant agent auth |
| `microsoft/azure-skills`  | `azure-prepare`                | SDD services beyond the azd AI starter, or explicitly chosen IaC/azd scaffolding in rapid mode |
| `microsoft/azure-skills`  | `azure-validate`               | Validation of an azd/IaC deployment, including configuration, RBAC and what-if checks |
| `microsoft/azure-skills`  | `azure-deploy`                 | Execution/recovery of a prepared azd/IaC deployment |
| `github/awesome-copilot`  | `microsoft-agent-framework`    | Basic agents or explicit agent workflows, or an explicit MAF choice; clarify workflows that also need runtime skills |
| `github/awesome-copilot`  | `copilot-sdk`                  | Agents using runtime skills, or an explicit Copilot SDK choice; BYOK Foundry models, toolbox tools/skills and the Responses API |
| `github/awesome-copilot`  | `python-mcp-server-generator`  | A Python MCP server (FastMCP, streamable HTTP) |

Build skills help the coding assistant build the app; [run skills](run-skills-catalog.md) are executed by the resulting agent. Follow current `microsoft-foundry` workflows for governed skill versions and toolbox configuration, and verify generated code against installed SDK APIs. Catalog selection must not override the mode defaults in `SKILL.md`. This skill, the canvas and the workflow ship with the `foundry-agentic-loop` plugin; do not install them as companions.
check_rbac_preflight.py 18.9 KB
"""Check the caller's RBAC before provisioning in a foundry-agentic-loop run.

Reference implementation for the `foundry-agentic-loop` skill's RBAC pre-flight
(see references/rbac-preflight.md). Copy into ./scripts/ of the generated repo
and run it *before* any provisioning, optionally as an `azd` preprovision hook.

The failure this guards against is an RBAC gap that surfaces mid-provisioning,
after partial resources exist, one scope at a time. So this check reports
*every* missing assignment at once, as principal -> scope -> role, with a
ready-to-run remediation block to hand to a subscription owner.

Required assignments come from the deployer-prerequisites table in
references/rbac-contract.md. Effective assignments are read with the Azure CLI
(`az role assignment list --include-inherited --include-groups`), so inherited
and group-derived grants count. Roles are matched by their built-in role
definition ID, so renames (Azure AI * -> Foundry *) do not break the check, and
a requirement is satisfied by an equivalent-or-broader role (Owner satisfies
Contributor), which is why a fully-permissioned run reports nothing. Custom
roles are not evaluated.

Verdicts:
    PASS     every required assignment is satisfied. Prints one summary line
             (nothing at all with --quiet).
    BLOCKED  at least one is missing. Prints the full list. Do not start provisioning.
    ERROR    the check could not be evaluated -- resolve it, don't skip it.

Usage:
    python check_rbac_preflight.py --subscription <sub-id>
    python check_rbac_preflight.py --subscription <sub-id> --resource-group rg-app
    python check_rbac_preflight.py --from-file observed.json --subscription <sub-id>

Environment (each has a matching flag):
    AZURE_SUBSCRIPTION_ID  target subscription (required)
    AZURE_RESOURCE_GROUP   pre-existing resource group, if the run targets one
    AZURE_AI_ACCOUNT_ID    existing Foundry AI account resource id, if brownfield
    AZURE_AI_PROJECT_ID    existing Foundry project resource id, if brownfield

Exit codes: 0 on PASS, 2 on BLOCKED, 1 on ERROR.
"""

from __future__ import annotations

import argparse
import json
import os
import shutil
import subprocess
import sys

REFERENCE = (
    "skills/foundry-agentic-loop/references/rbac-contract.md#deployer-prerequisites-pre-flight"
)

# Scope kinds, in the order they are reported.
SUBSCRIPTION = "subscription"
RESOURCE_GROUP = "resource_group"
AI_ACCOUNT = "ai_account"
AI_PROJECT = "ai_project"

# Built-in role definition IDs are stable; display names are not. Microsoft
# renamed the Azure AI roles to Foundry roles, so match on the ID and keep the
# current name for the report. Legacy names still resolve for --from-file input.
ROLES: dict[str, tuple[str, str]] = {
    "owner": ("8e3af657-a8ff-443c-a75c-2fe8c4bcb635", "Owner"),
    "contributor": ("b24988ac-6180-42a0-ab88-20f7382dd24c", "Contributor"),
    "user_access_admin": ("18d7d88d-d35e-4fb5-a5c3-7773c20a72d9", "User Access Administrator"),
    "rbac_admin": ("f58310d9-a9f6-439a-9e8d-f62e7b41a168", "Role Based Access Control Administrator"),
    "cs_contributor": ("25fbc0a9-bd7c-42a3-aa1a-3b75d497ee68", "Cognitive Services Contributor"),
    "foundry_owner": ("c883944f-8b7b-4483-af10-35834be79c4a", "Foundry Owner"),
    "foundry_account_owner": ("e47c6f54-e4a2-4754-9501-8e0985b135e1", "Foundry Account Owner"),
    "foundry_project_manager": ("eadc314b-1a2d-4efa-be10-5d325db5065e", "Foundry Project Manager"),
    "foundry_user": ("53ca6127-db72-4b80-b1b0-d745d6d5456d", "Foundry User"),
    "cs_user": ("a97b65f3-24c7-4388-baec-2e87135dc908", "Cognitive Services User"),
}
LEGACY_NAMES = {
    "Azure AI Owner": "foundry_owner",
    "Azure AI Account Owner": "foundry_account_owner",
    "Azure AI Project Manager": "foundry_project_manager",
    "Azure AI User": "foundry_user",
}
_BY_ID = {guid: key for key, (guid, _) in ROLES.items()}
_BY_NAME = {name.lower(): key for key, (_, name) in ROLES.items()} | {
    name.lower(): key for name, key in LEGACY_NAMES.items()
}

# Foundry control plane (Microsoft.CognitiveServices/* actions) versus data plane
# (Microsoft.CognitiveServices/* dataActions). Owner, Contributor, Foundry Account
# Owner and Cognitive Services Contributor carry no dataActions, so none of them
# can create agents alone; Foundry User and Cognitive Services User carry only
# dataActions, so neither can create project connections alone.
ACCOUNT_CONTROL = ["foundry_account_owner", "foundry_owner", "owner", "contributor", "cs_contributor"]
DATA_PLANE = ["foundry_user", "cs_user"]
DEPLOY = [{"contributor"}, {"owner"}]
ASSIGN = [{"rbac_admin"}, {"owner"}, {"user_access_admin"}]

# Required assignments per scope kind -- the deployer prerequisites table.
# A requirement is met when every role of any one alternative is effective at the
# scope. Remedies are tried in order and the first that completes an alternative
# is reported, so the remediation is the smallest grant that works.
REQUIREMENTS: list[dict] = [
    {
        "kind": SUBSCRIPTION,
        "why": "Create the resource group and every resource in the reference architecture",
        "alternatives": DEPLOY,
        "accepts": "Contributor | Owner",
        "remedies": [{"contributor"}],
    },
    {
        "kind": SUBSCRIPTION,
        "why": "Microsoft.Authorization/roleAssignments/write - the Bicep creates every row "
        "of the runtime matrix",
        "alternatives": ASSIGN,
        "accepts": "Role Based Access Control Administrator | Owner | User Access Administrator",
        "remedies": [{"rbac_admin"}],
    },
    {
        "kind": RESOURCE_GROUP,
        "why": "Create every resource of the solution in the existing resource group",
        "alternatives": DEPLOY,
        "accepts": "Contributor | Owner",
        "remedies": [{"contributor"}],
    },
    {
        "kind": RESOURCE_GROUP,
        "why": "Microsoft.Authorization/roleAssignments/write - create the runtime matrix rows "
        "in the resource group",
        "alternatives": ASSIGN,
        "accepts": "Role Based Access Control Administrator | Owner | User Access Administrator",
        "remedies": [{"rbac_admin"}],
    },
    {
        "kind": AI_ACCOUNT,
        "why": "Create projects, model deployments and account resources (control plane)",
        "alternatives": [{role} for role in ACCOUNT_CONTROL],
        "accepts": "Foundry Account Owner | Foundry Owner | Owner | Contributor | "
        "Cognitive Services Contributor",
        "remedies": [{"foundry_account_owner"}],
    },
    {
        "kind": AI_PROJECT,
        "why": "Create and publish hosted agents, skills, toolboxes (data plane) and project "
        "connections (control plane)",
        "alternatives": [{"foundry_project_manager"}, {"foundry_owner"}]
        + [{data, control} for data in DATA_PLANE for control in ACCOUNT_CONTROL],
        "accepts": "Foundry Project Manager | Foundry Owner | Foundry User (or Cognitive "
        "Services User) plus Foundry Account Owner, Owner, Contributor or Cognitive "
        "Services Contributor",
        "remedies": [{"foundry_user"}, {"foundry_project_manager"}],
    },
]


class PreflightError(Exception):
    """The check could not be evaluated (verdict ERROR)."""


def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument(
        "--subscription",
        default=os.environ.get("AZURE_SUBSCRIPTION_ID"),
        help="Target subscription id (default: $AZURE_SUBSCRIPTION_ID).",
    )
    parser.add_argument(
        "--resource-group",
        default=os.environ.get("AZURE_RESOURCE_GROUP"),
        help=(
            "Pre-existing resource group name (default: $AZURE_RESOURCE_GROUP). "
            "Omit on a greenfield run, where the deployment creates it."
        ),
    )
    parser.add_argument(
        "--ai-account",
        default=os.environ.get("AZURE_AI_ACCOUNT_ID"),
        help="Existing Foundry AI account resource id (default: $AZURE_AI_ACCOUNT_ID).",
    )
    parser.add_argument(
        "--ai-project",
        default=os.environ.get("AZURE_AI_PROJECT_ID"),
        help="Existing Foundry project resource id (default: $AZURE_AI_PROJECT_ID).",
    )
    parser.add_argument(
        "--assignee",
        help=(
            "Principal to check (object id or UPN). Defaults to the signed-in user, "
            "or to 'principal' in the --from-file payload."
        ),
    )
    parser.add_argument(
        "--from-file",
        help=(
            "Read observed assignments from a JSON file instead of calling Azure. "
            "Shape: {'principal': {'id': ..., 'display': ...}, "
            "'assignments': [{'scope': ..., 'role': <name or definition id>}, ...]}. "
            "Raw 'az role assignment list' output is accepted too."
        ),
    )
    parser.add_argument(
        "--quiet",
        action="store_true",
        help="Print nothing on PASS. The BLOCKED report is always printed.",
    )
    return parser.parse_args(argv)


def _az(args: list[str]) -> object:
    """Run an `az` command and return its parsed JSON output."""
    if shutil.which("az") is None:
        raise PreflightError(
            "Azure CLI ('az') not found on PATH -- required unless --from-file is used."
        )
    completed = subprocess.run(
        ["az", *args, "-o", "json"],
        capture_output=True,
        text=True,
        check=False,
    )
    if completed.returncode != 0:
        detail = (completed.stderr or completed.stdout).strip().splitlines()
        raise PreflightError(
            f"az {' '.join(args)} failed: {detail[-1] if detail else 'unknown error'}"
        )
    try:
        return json.loads(completed.stdout or "null")
    except json.JSONDecodeError as exc:
        raise PreflightError(f"az {' '.join(args)} returned non-JSON output: {exc}") from exc


def build_scopes(args: argparse.Namespace) -> list[tuple[str, str]]:
    """Return the (scope kind, scope id) pairs in play, in report order.

    An existing resource group carries the deployment, so its rows replace the
    subscription rows (subscription grants still satisfy them by inheritance).
    Without one, the subscription rows are checked because the run creates the
    group. Foundry scopes are checked when the run targets existing ones.
    """
    if not args.subscription:
        raise PreflightError(
            "No subscription: set AZURE_SUBSCRIPTION_ID or pass --subscription."
        )

    subscription_scope = f"/subscriptions/{args.subscription}"
    if args.resource_group:
        group = args.resource_group
        scopes = [
            (
                RESOURCE_GROUP,
                group
                if group.startswith("/subscriptions/")
                else f"{subscription_scope}/resourceGroups/{group}",
            )
        ]
    else:
        scopes = [(SUBSCRIPTION, subscription_scope)]
    if args.ai_account:
        scopes.append((AI_ACCOUNT, args.ai_account))
    if args.ai_project:
        scopes.append((AI_PROJECT, args.ai_project))
    return scopes


def drop_missing_group(scopes: list[tuple[str, str]], subscription: str) -> list[tuple[str, str]]:
    """Check the subscription rows instead when the resource group does not exist yet."""
    for index, (kind, scope) in enumerate(scopes):
        if kind != RESOURCE_GROUP:
            continue
        name = scope.rstrip("/").rsplit("/", 1)[-1]
        sub = scope.split("/")[2] if scope.startswith("/subscriptions/") else subscription
        if _az(["group", "exists", "--name", name, "--subscription", sub]) is False:
            scopes[index] = (SUBSCRIPTION, f"/subscriptions/{sub}")
    return scopes


def _role_key(item: dict) -> str:
    """Map an assignment to a ROLES key by definition ID, falling back to its name."""
    for field in ("roleDefinitionId", "role", "roleDefinitionName"):
        value = str(item.get(field) or "").strip()
        if not value:
            continue
        guid = value.rstrip("/").rsplit("/", 1)[-1].lower()
        if guid in _BY_ID:
            return _BY_ID[guid]
        if value.lower() in _BY_NAME:
            return _BY_NAME[value.lower()]
    return ""


def _normalize(assignments: object) -> list[dict[str, str]]:
    """Keep the known roles only; custom and unrelated roles satisfy nothing here."""
    records = []
    for item in assignments or []:
        if not isinstance(item, dict):
            continue
        scope = item.get("scope")
        role = _role_key(item)
        if scope and role:
            records.append({"scope": str(scope), "role": role})
    return records


def load_from_file(path: str, assignee: str | None) -> tuple[dict[str, str], list[dict[str, str]]]:
    """Load a recorded snapshot: {"principal": {"id", "display"}, "assignments": [...]}.

    A bare list of assignments carries no principal, so it needs --assignee; the
    report never prints a remediation command for an unknown principal.
    """
    try:
        with open(path, encoding="utf-8") as handle:
            payload = json.load(handle)
    except json.JSONDecodeError as exc:
        raise PreflightError(f"{path} is not valid JSON: {exc}") from exc
    if isinstance(payload, list):
        payload = {"assignments": payload}
    if not isinstance(payload, dict):
        raise PreflightError(f"{path} must hold an object or a list of assignments.")
    principal = payload.get("principal") or {}
    assignments = payload.get("assignments")
    if not isinstance(principal, dict) or not isinstance(assignments, list):
        raise PreflightError(
            f"{path} must hold 'principal' as an object and 'assignments' as a list."
        )
    principal_id = str(assignee or principal.get("id") or "").strip()
    if not principal_id:
        raise PreflightError(f"{path} names no principal -- pass --assignee.")
    resolved = {
        "id": principal_id,
        "display": str(principal.get("display") or principal_id),
    }
    return resolved, _normalize(assignments)


def resolve_principal(assignee: str | None) -> dict[str, str]:
    if assignee:
        return {"id": assignee, "display": assignee}
    user = _az(["ad", "signed-in-user", "show"])
    if not isinstance(user, dict) or not user.get("id"):
        raise PreflightError(
            "Could not resolve the signed-in user -- run 'az login' or pass --assignee."
        )
    return {
        "id": str(user["id"]),
        "display": str(user.get("userPrincipalName") or user.get("displayName") or user["id"]),
    }


def resolve_assignments(principal_id: str, scopes: list[tuple[str, str]]) -> list[dict[str, str]]:
    """Read effective assignments -- inherited and group-derived included."""
    records: list[dict[str, str]] = []
    for _, scope in scopes:
        listed = _az(
            [
                "role",
                "assignment",
                "list",
                "--assignee",
                principal_id,
                "--scope",
                scope,
                "--include-inherited",
                "--include-groups",
            ]
        )
        if not isinstance(listed, list):
            raise PreflightError(f"az role assignment list returned no list for {scope}.")
        records.extend(_normalize(listed))
    return records


def _covers(assignment_scope: str, scope: str) -> bool:
    """True when an assignment at `assignment_scope` applies to `scope`.

    An assignment inherits downwards, so a subscription-scoped grant satisfies a
    requirement on a resource group or Foundry project beneath it.
    """
    a = assignment_scope.rstrip("/").lower()
    s = scope.rstrip("/").lower()
    return s == a or s.startswith(f"{a}/")


def find_missing(
    scopes: list[tuple[str, str]], assignments: list[dict[str, str]]
) -> list[dict[str, object]]:
    """Diff required against effective, applying role and scope equivalence."""
    missing = []
    for kind, scope in scopes:
        effective = {
            record["role"] for record in assignments if _covers(record["scope"], scope)
        }
        for req in REQUIREMENTS:
            alternatives = req["alternatives"]
            if req["kind"] != kind or any(alt <= effective for alt in alternatives):
                continue
            remedy = next(
                (
                    grant
                    for grant in req["remedies"]
                    if any(alt <= effective | grant for alt in alternatives)
                ),
                req["remedies"][-1],
            )
            missing.append(
                {
                    "scope": scope,
                    "grant": sorted(remedy - effective),
                    "accepts": req["accepts"],
                    "why": req["why"],
                }
            )
    return missing


def report_blocked(principal: dict[str, str], missing: list[dict[str, object]]) -> None:
    count = len(missing)
    plural = "" if count == 1 else "s"
    print(
        f"RBAC pre-flight: BLOCKED -- {count} required role assignment{plural} "
        f"{'is' if count == 1 else 'are'} missing."
    )
    print()
    print(f"  principal: {principal['display']} ({principal['id']})")
    print()
    for gap in missing:
        grant = ", ".join(f"{ROLES[key][1]} ({ROLES[key][0]})" for key in gap["grant"])
        print(f"  MISSING  {principal['display']} -> {gap['scope']}")
        print(f"           grant:   {grant}")
        print(f"           accepts: {gap['accepts']}")
        print(f"           why:     {gap['why']}")
    print()
    print("Ask a subscription owner to run (role definition IDs are stable across renames):")
    print()
    for gap in missing:
        for key in gap["grant"]:
            print(
                f'  az role assignment create --assignee "{principal["id"]}" '
                f'--role "{ROLES[key][0]}" --scope "{gap["scope"]}"'
            )
    print()
    print(f"reference: {REFERENCE}")
    print("No resources have been created. Re-run this check once the assignments are in place.")


def main(argv: list[str] | None = None) -> int:
    args = _parse_args(argv)

    try:
        scopes = build_scopes(args)
        if args.from_file:
            principal, assignments = load_from_file(args.from_file, args.assignee)
        else:
            scopes = drop_missing_group(scopes, args.subscription)
            principal = resolve_principal(args.assignee)
            assignments = resolve_assignments(principal["id"], scopes)
    except (PreflightError, OSError) as exc:
        print(f"RBAC pre-flight: ERROR -- {exc}", file=sys.stderr)
        return 1
    except (TypeError, ValueError, KeyError, AttributeError) as exc:
        print(f"RBAC pre-flight: ERROR -- unexpected input shape: {exc}", file=sys.stderr)
        return 1

    missing = find_missing(scopes, assignments)
    if missing:
        report_blocked(principal, missing)
        return 2

    if not args.quiet:
        required = sum(1 for kind, _ in scopes for req in REQUIREMENTS if req["kind"] == kind)
        checked = ", ".join(kind.replace("_", " ") for kind, _ in scopes)
        print(
            f"RBAC pre-flight: PASS -- {required} required role assignments satisfied "
            f"({checked})."
        )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
copilot-sdk-foundry.md 16.6 KB
# Copilot SDK with Foundry

Read only for Copilot SDK agents, SDK/identity troubleshooting, or the dependency-packaging fallback. Continue using Microsoft Agent Framework when the architecture selects it; this recipe does not change framework defaults.

**Recipe revision 3 (2026-10-19).** Configuration/signatures were source-checked against `github/copilot-sdk` **v1.0.14** and re-inspected on the installed packages below. The "v1.0.14" labels mark the first checked release, not an upper bound. This is not a claim that every SDK/runtime pair has passed a hosted deployment. Keep the project's approved compatible pins; record and validate its actual combination at the [hosted checkpoint](hosted-integration-checkpoint.md).

| Surface used by this recipe | 1.0.14 | 1.0.20 (installed check) | Later |
| --- | --- | --- | --- |
| `create_session(*, provider=..., mcp_servers=...)` keyword-only | yes | yes | inspect |
| `send_and_wait(prompt: str, *, request_headers=...)` | yes | yes | inspect |
| `ProviderConfig.bearer_token_provider` refresh callback | yes | yes | inspect |
| `MCPHTTPServerConfig.headers` static dict (no refresh callback) | yes | yes | inspect |
| `CopilotClient(telemetry=TelemetryConfig)` and `get_status().version` | yes | yes | inspect |
| `azure-ai-agentserver-responses` `ResponseEventStream` items ([hosted agent](foundry-hosted-agent.md#hosted-agent-protocol)) | 2.2.0 | 2.3.0 | inspect |

For an unlisted version, inspect these signatures before coding and record the result with the compatibility record.

## Compatibility record first

Before troubleshooting, record Python (retain **3.13**), `github-copilot-sdk`, Azure Identity, project/hosting-adapter versions, lockfile hash and the **running Copilot runtime version**. In v1.0.14, after client startup, `(await client.get_status()).version` reports that runtime; `importlib.metadata.version("github-copilot-sdk")` reports the Python package. Do not assume the developer shell's `copilot --version` is the deployed runtime.

Inspect installed signatures/types, particularly `CopilotClient.create_session`, `CopilotSession.send_and_wait`, `ProviderConfig` and the hosting request-context accessor. The v1.0.14 Python interface uses keyword arguments for `create_session`, a string prompt for `send_and_wait`, and `request_headers` for per-turn model headers. Older examples accepting config/message dictionaries are not interchangeable. The bearer-token callback surface is experimental in this release: check the runtime supports its protocol; never silently replace an unsupported refresh callback with a static token. Use the SDK-supported runtime distribution and pin the validated combination.

## Model configuration and token refresh

For the discovered OpenAI-compatible **`/openai/v1/`** base, use `type: "openai"` and `wire_api: "responses"`. Keep the Basic sample's actual deployment or the user's existing deployment; a model catalog name is not necessarily its deployment name. Do not mix this route with the native `type: "azure"` host-only recipe or with the hosted-agent Responses endpoint.

The following provider fragment uses v1.0.14 fields. `credential` must be the approved **deployed workload** async credential in hosted runs; select it through current `microsoft-foundry` guidance. `token_scope` comes from the verified endpoint contract (the documented Foundry path uses `https://ai.azure.com/.default`); verify the audience for a different Azure endpoint rather than assuming it.

```python
from azure.core.credentials_async import AsyncTokenCredential
from copilot.session import ProviderConfig, ProviderTokenArgs

def model_provider(
    base_url: str,
    token_scope: str,
    credential: AsyncTokenCredential,
) -> ProviderConfig:
    async def refresh_token(_request: ProviderTokenArgs) -> str:
        return (await credential.get_token(token_scope)).token

    return {
        "type": "openai",
        "base_url": base_url,
        "wire_api": "responses",
        "bearer_token_provider": refresh_token,
    }
```

The SDK requests a token before outbound provider calls; Azure Identity handles caching/renewal. Keep that credential alive for its owning client and close it on shutdown. Do not capture one startup token in `bearer_token`, `.env` or a long-lived Authorization header. Test another request after simulated expiry; no new deployment should be needed.

Create the session with the verified provider and deployment using an explicit least-privilege permission handler, not an unrestricted approval shortcut. Subscribe to errors and execution events before sending; `send_and_wait`/`session.idle` alone is not the hosted Responses success condition. Its timeout does not abort in-flight work: explicitly cancel/clean up the task-owned request through supported lifecycle APIs. Use the checkpoint's terminal-status and schema validation.

## Hosted caller-context forwarding

Use the current hosting adapter's request-context accessor; verify its installed API instead of guessing imports. For **container protocol 2.0.0**, the documented outbound caller-context header is **`x-agent-foundry-call-id`**. Forward its opaque value unchanged to the configured Foundry **model and toolbox** requests. The platform-generated **`x-agent-user-id` is local partitioning context and must not be forwarded outbound**. Do not copy all inbound headers, trust caller-supplied `x-client-*` as identity, or propagate incoming Authorization/cookies.

- Capture an allowlisted copy of context for each hosted request. Pass the call ID through `session.send_and_wait(prompt, request_headers=foundry_headers)` for the model request in v1.0.14. For adapters using provider `headers`, isolate the provider/session per request; never mutate a global header dictionary.
- Pass the same request's call ID to MCP `tools/list`, skill-loading and `tools/call` requests. Use the platform-aware toolbox client or a request-local MCP adapter that acquires/refreshes its own token for the toolbox audience. A Copilot model `bearer_token_provider` does **not** refresh MCP credentials.
- In v1.0.14, remote MCP configuration exposes `headers` as a static dictionary, not a token-refresh callback. Do not invent a callback field or keep a startup bearer token there indefinitely. Use a supported refreshing MCP transport, or a request-scoped connection with explicit token lifetime/reconnect handling; retain least-privilege tool approval.
- Bind SDK sessions, callbacks and MCP connections to the originating caller/turn. Capture request context before crossing async/process boundaries; callbacks may run outside the hosting context variable. Isolate concurrent sessions or serialize same-session turns so headers/results cannot cross requests.
- Only send platform context to the intended trusted Foundry endpoints, never arbitrary tool URLs or logs. Toolbox connections govern downstream credentials. For local-only tests, absent platform context can be legitimate; do not fabricate call IDs. If a deployed path requires context and it is absent, fail that probe explicitly.

Verify actual outbound header **presence and request association** with redacted instrumentation, including two concurrent requests and token renewal. Do not merely inspect configuration or use an SDK mock as proof that the hosted runtime forwarded it.

## Telemetry

Configure telemetry in the minimal slice, before deployment. The Python hosting adapter and Copilot runtime are separate telemetry producers: a project connection or Python exporter alone does not prove that runtime model/tool spans are exported.

1. **Record the route.** Add the hosting/Copilot SDK and running runtime versions, export paths, discovered receiver endpoints and exporting identities/scopes to the root `README.md` (rapid) or `docs/implementation.md` (SDD), and the Application Insights resource ID to `.azure/deployment-plan.md`. Keep connection configuration in the appropriate deployment settings and Git-ignored `.env`, not diagnostic logs. Resolve the selected project's linked Application Insights through `microsoft-foundry`; prefer its azd-owned values over duplicated metadata. Do not silently use a different destination.
2. **Configure the host once.** Load telemetry configuration before constructing the hosting adapter. Current AgentServer Core initializes observability through `microsoft-opentelemetry`, supports Azure Monitor export with `APPLICATIONINSIGHTS_CONNECTION_STRING`, and supports OTLP export with `OTEL_EXPORTER_OTLP_ENDPOINT`. Inspect the installed adapter's behavior before using these settings; do not independently initialize a duplicate global provider/exporter. Generic HTTP-client instrumentation is disabled by default in the inspected source: enable only needed supported instrumentation or add explicit spans at owned MCP/application boundaries.
3. **Configure the runtime explicitly.** Merge the following v1.0.14 fragment into the existing client's configuration rather than creating a second runtime. `COPILOT_OTLP_ENDPOINT` is an application-defined variable containing a verified, reachable OTLP HTTP receiver base URL, not an Application Insights connection string or ordinary ingestion URL.

   ```python
   import os
   from copilot import CopilotClient

   client = CopilotClient(
       telemetry={
           "otlp_endpoint": os.environ["COPILOT_OTLP_ENDPOINT"],
           "otlp_protocol": "http/protobuf",
           "exporter_type": "otlp-http",
           "capture_content": False,
       },
   )
   ```

   Verify the receiver's supported onward export to the intended Azure Monitor/Application Insights destination. Reuse a working route; obtain approval before provisioning a collector or other ingestion resources. Native Azure Monitor OTLP ingestion requires its discovered endpoints, Data Collection Rule (DCR) and authentication; an ordinary connection string does not configure that route. Do not point an HTTP/protobuf client at a gRPC-only receiver or assume the Python host is an OTLP receiver.
4. **Check the actual exporter identity.** Verify supported authentication for the installed version and chosen route. Current Core source supports `APPLICATIONINSIGHTS_AUTH_MODE=entra` using managed identity for Azure Monitor export. Direct authenticated Application Insights ingestion requires the actual emitter's applicable permission on the component; native OTLP collector ingestion requires the collector identity's Monitoring Metrics Publisher role on the DCR. A remote collector can have a different identity from the agent. Recheck actual principals after deployment and defer current role/resource mechanics to `microsoft-foundry`; do not grant both scopes indiscriminately.
5. **Preserve distributed trace context.** Keep session creation/resume/send under the intended active hosting-request span. With OpenTelemetry available and configured, v1.0.14 Python propagates W3C `traceparent`/`tracestate` into the runtime and restores context around tool callbacks. Preserve context through supported MCP transports or owned boundary instrumentation. Test concurrent requests for correct trace/parent association; never use a global mutable trace-header dictionary. W3C tracing is separate from `x-agent-foundry-call-id` authentication context; neither substitutes for the other. Do not fabricate remote child spans as execution evidence.
6. **Keep content private.** Keep Copilot `capture_content=False` and hosting sensitive-data capture disabled unless explicitly approved with redaction and retention controls. These options do not sanitize explicit application, adapter or tool logs: avoid prompts, completions, tool arguments/results, credentials and opaque caller-context values. Record safe identifiers, status, duration and available usage metadata instead.
7. **Verify delivery and lifecycle.** Start instrumentation before requests and shut down the runtime/flush owned exporters through supported graceful-lifecycle APIs. Record sampling and ensure checkpoint probes are retained without silently changing production policy. Allow bounded batching/ingestion delay, then require the deployed probe's hosting, model and required tool spans with correct trace/parent links and agent/version identification. Follow the Foundry trace workflow: for its Application Insights schema, start from `requests` filtered by agent name and join `dependencies` by `operation_Id`. Verify the actual schema for native OTLP ingestion instead of assuming those tables. Host-only spans, exporter startup and local mocks do not satisfy the checkpoint.

If spans are missing, inspect producer enablement, active context, receiver reachability, destination/authentication, sampling and flush/ingestion delay before changing code or infrastructure. Report the failed boundary and keep the checkpoint blocked; do not redeploy an unchanged artifact to wait for telemetry.

## Dependency-packaging fallback

Remote build remains the default. When server-side dependency resolution fails, first capture the restore error and correct invalid/incompatible requirements. For access/feed failures, follow the approved package-feed guidance; do not disable TLS or integrity checks. If remote resolution still cannot work, use the supported **bundled source-code deployment** mode through `microsoft-foundry`, not an unrequested container-image migration.

1. Export the approved lockfile to a fully pinned, hashed requirements file, including transitive dependencies and the **target Linux wheel hashes**. Preserve private feeds/pins. Work in a fresh, task-owned staging directory; do not reuse a macOS/Windows virtualenv.
2. For the currently documented Linux x86_64 Python 3.13 runtime, install extracted modules into `packages/`:

   ```bash
   python3.13 -m pip install --require-hashes -r requirements.lock \
     --target packages/ --platform manylinux2014_x86_64 \
     --python-version 3.13 --implementation cp --only-binary=:all:
   ```

   `requirements.lock` here is the exported pip-compatible hash-locked file. If required wheels are unavailable, report the package/platform blocker; use a reproducible matching Linux build with verified artifacts rather than silently dropping hashes or shipping host-native binaries.
3. Validate imports and runtime startup in matching Linux/Python 3.13. The Copilot runtime/native assets are separate from Python wheels: resolve the SDK-supported Linux runtime, preserve executable permissions, and record its version/checksum. Do not bundle the developer's desktop binary or depend on an untested first-start download.
4. Produce a flat deployment archive with entry point, application sources, locked requirements, required assets and extracted `packages/` at the root. Set `runtime: python_3_13` and `dependency_resolution: bundled` using the current platform/tool schema. Inspect the archive and confirm packaging ignore rules did not remove `packages/`; compute and verify the deployed ZIP hash.
5. Exclude staging directories, `packages/`, runtime binaries and deployment archives from **Git and pytest discovery** (`testpaths`/`norecursedirs` or the repository's equivalent), but explicitly include required artifacts in the deployment ZIP. Keep the lockfile and packaging instructions in Git. Exclude `.env`, caches, credentials and unrelated files from the archive.
6. Redeploy this changed artifact once, rerun the hosted checkpoint, and record the reason for bundling plus versions/hash. A successful upload or `active` state is not acceptance. Remove only task-created staging/debug resources afterward.

## Versioned sources

- [v1.0.14 BYOK configuration](https://github.com/github/copilot-sdk/blob/v1.0.14/docs/auth/byok.md)
- [v1.0.14 managed identity and token refresh](https://github.com/github/copilot-sdk/blob/v1.0.14/docs/setup/azure-managed-identity.md)
- [v1.0.14 Python provider, MCP and session types](https://github.com/github/copilot-sdk/blob/v1.0.14/python/copilot/session.py)
- [v1.0.14 client signatures and runtime status](https://github.com/github/copilot-sdk/blob/v1.0.14/python/copilot/client.py)
- [v1.0.14 runtime telemetry configuration](https://github.com/github/copilot-sdk/blob/v1.0.14/docs/observability/opentelemetry.md)
- [v1.0.14 Python trace-context propagation](https://github.com/github/copilot-sdk/blob/v1.0.14/python/copilot/_telemetry.py)
- [AgentServer Core observability source (moving main; verify installed version)](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/agentserver/azure-ai-agentserver-core/azure/ai/agentserver/core/_tracing.py)
- [Azure Monitor native OTLP ingestion and DCR permissions](https://learn.microsoft.com/azure/azure-monitor/containers/opentelemetry-protocol-ingestion)
- [Foundry platform headers](https://learn.microsoft.com/azure/foundry/agents/concepts/hosted-agent-contract#platform-request-headers-container-protocol-200)
- [Supported bundled code-deployment layout](https://learn.microsoft.com/azure/foundry/agents/how-to/deploy-hosted-agent-code#package-the-zip-manually)
copilot-sdk-with-toolbox.py 14.3 KB
"""Reference hosted agent: GitHub Copilot SDK + Foundry toolbox (tools and skills over MCP).

Reference only: copilot-sdk-foundry.md is the recipe and wins on any conflict. Written against
github-copilot-sdk 1.0.14 and re-checked on 1.0.20; inspect the installed APIs first. Call `run_turn` from the Responses
handler that `azd ai agent init` scaffolds: create one credential and one client at startup and
close them at shutdown, pass the request's `x-agent-foundry-call-id` from the adapter's verified
request-context accessor, and stream the returned tool calls as output items before the message
(foundry-hosted-agent.md). Return a ToolboxError that has a consent_url to the caller as the
answer: the first use of an OAuth connection needs one sign-in per user.

    pip install "github-copilot-sdk[telemetry]" azure-identity

Environment (the agent's `env` in azure.yaml; FOUNDRY_* and AGENT_* are platform-reserved):
  TOOLBOX_ENDPOINT                Consumer URL <project>/toolboxes/<name>/mcp?api-version=v1, mapped
                                  from TOOLBOX_<NAME>_MCP_ENDPOINT; it serves the default version.
  MODEL_API_BASE_URL              The discovered .../openai/v1/ base and its deployment. Required
  AZURE_AI_MODEL_DEPLOYMENT_NAME  when hosted; locally, unset means the Copilot default model.
  COPILOT_OTLP_ENDPOINT           Optional OTLP HTTP receiver for runtime spans.

Skills attached to the toolbox are MCP resources (skill://<name>/SKILL.md) that follow each
skill's default version, so publishing a skill needs no redeploy. For multi-file skills, or
skills outside a toolbox, use the Skills API download in microsoft-foundry. Verify that served
bodies keep their frontmatter; load_skills rebuilds it when missing.
"""

from __future__ import annotations

import asyncio
import json
import logging
import os
import re
import tempfile
from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

import httpx
from azure.core.credentials_async import AsyncTokenCredential
from azure.identity.aio import DefaultAzureCredential
from copilot import CopilotClient, SessionEventType, Tool, ToolInvocation, ToolResult
from copilot.generated.rpc import PermissionDecisionApproveOnce, PermissionDecisionReject
from copilot.generated.session_events import PermissionRequestCustomTool, PermissionRequestRead
from copilot.session import ProviderConfig, ProviderTokenArgs
from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode

log = logging.getLogger("agent")
tracer = trace.get_tracer(__name__)

SCOPE = "https://ai.azure.com/.default"  # model and toolbox audience; cognitiveservices gets 401
TOOLBOX_ENDPOINT = os.environ["TOOLBOX_ENDPOINT"]
MODEL_BASE_URL = os.getenv("MODEL_API_BASE_URL")
MODEL_DEPLOYMENT = os.getenv("AZURE_AI_MODEL_DEPLOYMENT_NAME")
if bool(MODEL_BASE_URL) != bool(MODEL_DEPLOYMENT):
    # One without the other would silently fall back to the Copilot default model.
    raise RuntimeError("Set both MODEL_API_BASE_URL and AZURE_AI_MODEL_DEPLOYMENT_NAME, or neither.")
WRITABLE = Path(tempfile.gettempdir())  # hosted containers are read-only except the temp dir
SKILL_URI = re.compile(r"skill://([A-Za-z0-9_-]+)/SKILL\.md")
TURN_TIMEOUT = 300.0


@dataclass
class ToolCall:
    """One toolbox call, emitted as function_call and function_call_output items."""

    call_id: str
    name: str
    arguments: str
    output: str


@dataclass
class Turn:
    text: str
    tool_calls: list[ToolCall] = field(default_factory=list)


class ToolboxError(RuntimeError):
    """A toolbox JSON-RPC error; `consent_url` is set when a connection needs user consent."""

    def __init__(self, message: str, consent_url: str | None = None) -> None:
        super().__init__(message)
        self.consent_url = consent_url


def _toolbox_error(error: dict[str, Any]) -> ToolboxError:
    message = str(error.get("message", ""))
    if error.get("code") == -32006 and "{" in message:
        try:  # -32006 wraps per-source errors as JSON after a human-readable prefix
            for source in json.loads(message[message.index("{") :]).get("errors", []):
                nested = source.get("error") or {}
                if nested.get("code") == "CONSENT_REQUIRED":
                    url = nested.get("message")
                    name = source.get("name", "A toolbox connection")
                    return ToolboxError(f"{name} needs consent: open {url}, sign in, then retry.", url)
        except (ValueError, AttributeError):
            pass
    return ToolboxError(f"Toolbox error {error.get('code')}: {message or 'unknown'}")


class _Bearer(httpx.Auth):
    """Adds a token to every request; Azure Identity caches and renews it."""

    def __init__(self, credential: AsyncTokenCredential) -> None:
        self._credential = credential

    async def async_auth_flow(self, request: httpx.Request):
        request.headers["Authorization"] = f"Bearer {(await self._credential.get_token(SCOPE)).token}"
        yield request


class McpBridge:
    """Request-scoped JSON-RPC client for the toolbox MCP endpoint; initialize is optional."""

    def __init__(self, credential: AsyncTokenCredential, call_id: str | None) -> None:
        headers = {"Foundry-Features": "Toolboxes=V1Preview"}
        if call_id:  # forward the caller context unchanged; never fabricate one
            headers["x-agent-foundry-call-id"] = call_id
        self._http = httpx.AsyncClient(auth=_Bearer(credential), headers=headers, timeout=60.0)
        self._next_id = 0

    async def __aenter__(self) -> McpBridge:
        return self

    async def __aexit__(self, *_exc: object) -> None:
        await self._http.aclose()

    async def rpc(self, method: str, params: dict[str, Any], target: str = "") -> dict[str, Any]:
        """One JSON-RPC call in an MCP client span that records no arguments or results."""
        self._next_id += 1
        payload = {"jsonrpc": "2.0", "id": self._next_id, "method": method, "params": params}
        name = f"{method} {target}".strip()
        with tracer.start_as_current_span(
            name, record_exception=False, set_status_on_exception=False
        ) as span:
            span.set_attribute("mcp.method.name", method)
            if method == "tools/call":
                span.set_attribute("gen_ai.tool.name", target)
            try:
                response = await self._http.post(TOOLBOX_ENDPOINT, json=payload)
                response.raise_for_status()
                body = response.json()
                if "error" in body:
                    raise _toolbox_error(body["error"])
            except Exception as exc:
                span.set_status(Status(StatusCode.ERROR))
                span.set_attribute("error.type", type(exc).__name__)
                raise
        return body.get("result") or {}


def _call_handler(toolbox: McpBridge, mcp_name: str, calls: list[ToolCall]):
    async def handler(invocation: ToolInvocation) -> ToolResult:
        arguments = invocation.arguments if isinstance(invocation.arguments, dict) else {}
        try:
            result = await toolbox.rpc("tools/call", {"name": mcp_name, "arguments": arguments}, mcp_name)
        except Exception as exc:  # report to the model; it can retry or explain
            output, outcome = str(exc), ToolResult(result_type="failure", error=str(exc))
        else:
            texts = [c.get("text", "") for c in result.get("content", []) if c.get("type") == "text"]
            output = "\n".join(t for t in texts if t) or json.dumps(result)
            failed = bool(result.get("isError"))
            outcome = ToolResult(
                text_result_for_llm=output,
                result_type="failure" if failed else "success",
                error=output if failed else None,
            )
        calls.append(ToolCall(invocation.tool_call_id, mcp_name, json.dumps(arguments), output))
        return outcome

    return handler


def toolbox_tools(toolbox: McpBridge, listed: list[dict[str, Any]], calls: list[ToolCall]) -> list[Tool]:
    """Wrap each tools/list entry as an SDK tool; MCP-sourced names look like label___tool."""
    tools: dict[str, Tool] = {}
    sources: dict[str, str] = {}
    for spec in listed:
        mcp_name = spec["name"]
        name = re.sub(r"[.-]", "_", mcp_name)  # SDK tool names reject dots and hyphens
        if name in sources:
            # Dropping one would silently change the agent's capabilities; rename a tool instead.
            raise ValueError(f"Toolbox tools {sources[name]!r} and {mcp_name!r} both map to {name!r}.")
        sources[name] = mcp_name
        tools[name] = Tool(
            name=name,
            description=spec.get("description") or mcp_name,
            parameters=spec.get("inputSchema") or {"type": "object", "properties": {}},
            handler=_call_handler(toolbox, mcp_name, calls),
        )
    return list(tools.values())


async def load_skills(toolbox: McpBridge, skills_dir: Path) -> list[str]:
    """Write each toolbox skill to <skills_dir>/<name>/SKILL.md for the SDK skill loader."""
    names: list[str] = []
    for resource in (await toolbox.rpc("resources/list", {})).get("resources", []):
        match = SKILL_URI.fullmatch(resource.get("uri", ""))
        if not match:
            continue  # skill://index.json, archives and other resources
        name = match.group(1)
        read = await toolbox.rpc("resources/read", {"uri": resource["uri"]}, name)
        body = "".join(c.get("text", "") for c in read.get("contents", []))
        if not body.lstrip().startswith("---"):
            description = json.dumps(resource.get("description") or name)
            body = f"---\nname: {name}\ndescription: {description}\n---\n\n{body}"
        (skills_dir / name).mkdir(parents=True, exist_ok=True)
        (skills_dir / name / "SKILL.md").write_text(body, encoding="utf-8")
        names.append(name)
    return names


def model_provider(credential: AsyncTokenCredential) -> ProviderConfig:
    async def refresh_token(_request: ProviderTokenArgs) -> str:
        return (await credential.get_token(SCOPE)).token

    return {
        "type": "openai",
        "base_url": MODEL_BASE_URL,
        "wire_api": "responses",
        "bearer_token_provider": refresh_token,
    }


def least_privilege(tool_names: set[str], skills_dir: Path) -> Callable[[Any, Any], Any]:
    """Approve this turn's toolbox tools and reads of its skills; reject everything else."""

    def decide(request: Any, _invocation: Any) -> Any:
        if isinstance(request, PermissionRequestCustomTool) and request.tool_name in tool_names:
            return PermissionDecisionApproveOnce()
        if isinstance(request, PermissionRequestRead):
            if Path(request.resolved_path or request.path).resolve().is_relative_to(skills_dir):
                return PermissionDecisionApproveOnce()
        return PermissionDecisionReject(feedback="Not permitted for this agent.")

    return decide


def log_event(event: Any) -> None:
    """Log safe identifiers only: never prompts, arguments, results or caller context."""
    data = event.data
    if event.type == SessionEventType.SESSION_ERROR:
        log.error(
            "session error type=%s code=%s status=%s request=%s",
            data.error_type, data.error_code, data.status_code, data.service_request_id,
        )
    elif event.type == SessionEventType.TOOL_EXECUTION_START:
        log.info("tool start %s id=%s", data.tool_name, data.tool_call_id)
    elif event.type == SessionEventType.TOOL_EXECUTION_COMPLETE:
        log.info("tool done id=%s success=%s", data.tool_call_id, data.success)


def new_client() -> CopilotClient:
    """One Copilot runtime per process."""
    options: dict[str, Any] = {}
    if not os.access(Path.home(), os.W_OK):  # session state defaults to ~/.copilot
        options["base_directory"] = str(WRITABLE / "copilot")
    if endpoint := os.getenv("COPILOT_OTLP_ENDPOINT"):
        options["telemetry"] = {
            "otlp_endpoint": endpoint,
            "otlp_protocol": "http/protobuf",
            "exporter_type": "otlp-http",
            "capture_content": False,
        }
    return CopilotClient(**options)


async def run_turn(
    client: CopilotClient, credential: AsyncTokenCredential, prompt: str, call_id: str | None = None
) -> Turn:
    """Run one request with its own toolbox connection, skills directory and session."""
    calls: list[ToolCall] = []
    headers = {"x-agent-foundry-call-id": call_id} if call_id else None
    options: dict[str, Any] = {}
    if MODEL_BASE_URL:
        options = {"provider": model_provider(credential), "model": MODEL_DEPLOYMENT}
    async with McpBridge(credential, call_id) as toolbox:
        tools = toolbox_tools(toolbox, (await toolbox.rpc("tools/list", {})).get("tools", []), calls)
        with tempfile.TemporaryDirectory(prefix="turn-", dir=WRITABLE) as workdir:
            skills_dir = Path(workdir).resolve() / "skills"
            await load_skills(toolbox, skills_dir)
            async with await client.create_session(
                **options,
                tools=tools,
                skill_directories=[str(skills_dir)],
                working_directory=workdir,
                on_permission_request=least_privilege({tool.name for tool in tools}, skills_dir),
                on_event=log_event,
            ) as session:
                try:
                    reply = await session.send_and_wait(
                        prompt, request_headers=headers, timeout=TURN_TIMEOUT
                    )
                except TimeoutError:
                    await session.abort()  # the timeout alone leaves the turn running
                    raise
    if reply is None or not reply.data.content:
        raise RuntimeError("The session ended without an assistant message.")
    return Turn(reply.data.content, calls)


async def main() -> None:
    """Local smoke run: `az login`, set TOOLBOX_ENDPOINT, optionally the model pair."""
    logging.basicConfig(level=logging.INFO)
    async with DefaultAzureCredential() as credential, new_client() as client:
        try:
            turn = await run_turn(client, credential, "Which tools and skills can you use? Be brief.")
        except ToolboxError as exc:
            if exc.consent_url is None:
                raise
            print(exc)
            return
        for call in turn.tool_calls:
            print(f"tool {call.name}: {len(call.output)} chars")
        print(turn.text)


if __name__ == "__main__":
    asyncio.run(main())
deploy.md 4.4 KB
# Deploy phase

Ship the verified solution to the target in `.azure/deployment-plan.md`. Apply the [skill defaults](../SKILL.md#defaults) and use `microsoft-foundry` for platform operations. Run azd from the workspace root, with `AZURE_DEV_USER_AGENT=microsoft_foundry_skill` set inline.

## 1. Preflight

Run these checks read-only and report every gap at once.

- **Tools:** `az`, `azd` and `bicep` work. `azd ext list` meets `requiredVersions` in `azure.yaml`. `azd auth login --check-status` succeeds. If az is signed in but azd is not, run `azd config set auth.useAzCliAuth true`.
- **Target:** `azd env get-values` matches the deployment plan's subscription, resource group, region and environment. Stop on any mismatch.
- **Packaging:**
  - Agents ship `uv.lock` or pinned requirements, never the `agent-framework` meta-package.
  - Agents have `.agentignore`; containers have `.dockerignore`.
  - Entrypoints use LF line endings (`.gitattributes`).
  - Telemetry is enabled in every component.

## 2. Deploy

Inside a workflow run, the `approve-deploy-v1` (or a later `approve-deploy-r<n>[-a<k>]-v1`) approval covers this section only for the fingerprint it recorded: first confirm `azd env get-values` and `az account show` match the approved environment, subscription, location, resource group and Foundry account, project and resource group, and if any differs, change nothing and report blocked. Report each health and E2E check as an evidence item. Otherwise ask first, summarizing the resources, cost, security and region impact for the named environment and subscription.

1. When the infrastructure changed, run `azd provision --preview <layer> --no-prompt` for each `infra.layers` name (a plain `--preview` fails on multiple layers) and review deletions and replacements. Stop on surprises.
2. Run `azd up --no-prompt`, or `azd deploy --no-prompt` when the infrastructure is unchanged. Wait for it to finish, record the exit code, and read back the [grants after deploy](azd-layout.md#grants-after-deploy).
3. Read the endpoints from `azd env get-values` (`SERVICE_<NAME>_URI`, `AGENT_<NAME>_RESPONSES_ENDPOINT`). Confirm each container app has an active, healthy revision (`az containerapp revision list`).
4. For each agent, run:
   - `azd ai agent show <agent>` to get the endpoint and playground URL;
   - `azd ai agent invoke <agent> "<scenario>"`;
   - `azd ai agent monitor <agent> --session-id <id>`, with the ID from the invoke's `Session:` line, to read its logs.

   Retry 424 `session_not_ready` or 502 warm-up responses with backoff for up to 5 minutes.
5. Rerun the E2E suite against the deployed frontend at the concurrency recorded in `docs/verify.md`, plus every check it defers to Deploy.

## 3. Common failures

| Symptom | Fix |
| --- | --- |
| `QuotaExceeded`, `InsufficientQuota` | Rerun the placement check in another approved region, or lower capacity |
| `Conflict` (name taken), soft-deleted account | Add a suffix to the environment, or purge with approval |
| `ImagePullBackOff` | Check ACR push, AcrPull for the app identity and `AZURE_CONTAINER_REGISTRY_ENDPOINT` |
| `InvalidTemplate`, `InvalidResourceName` | Run `az bicep build`; check AVM versions and name limits |
| `AuthorizationFailed` | Run the RBAC preflight and hand the owner the grant block |
| `Hosted agents can only be called through the agent endpoint` | Call `{project}/agents/{agent}/endpoint/protocols/openai` with the `https://ai.azure.com/.default` scope |
| Agent dependency resolution fails | Pin sub-packages and their transitive imports |
| Hook fails with missing `AZURE_TENANT_ID` or an `AGENT_*` variable | Export it from `azd env get-values` in the hook; order hooks after deploy |

## 4. Record

1. Upsert `DEPLOYED_FRONTEND` in `.env`.
2. Write `docs/deploy.md` with:
   - the environment, subscription, resource group and region;
   - resources and agent versions;
   - endpoints and playground links;
   - check results;
   - cost drivers;
   - rollback (`azd deploy` of the previous version) and teardown (`azd down --purge`, then the Entra app registrations from `docs/implementation.md`, only with approval).
3. Refresh the root `README.md` with the overview, architecture, how to run and deploy, and links to all `docs/`.

## Gate

Pass only when:

- azd exits 0;
- revisions are healthy;
- each hosted agent answers;
- the deployed E2E suite and the deferred checks pass.

Report status, summary, artifacts, assumptions, issues, lessons, and endpoints as `{name, url}`.
foundry-hosted-agent.md 6.0 KB
# Foundry hosted agent

Reference for the `foundry-agentic-loop` skill: runtime concerns for an agent hosted on Microsoft Foundry. Hosted agents should expose the **Responses API** by default; use invocations only when explicitly required for compatibility. `foundry-agentic-loop` decides *that* the agent is hosted and *which framework* it uses; this file holds the hosted-agent runtime detail. The reference agent is [`copilot-sdk-with-toolbox.py`](copilot-sdk-with-toolbox.py).

## Hosted-agent protocol

Default to the **Responses API** protocol for hosted agents. Responses exposes an OpenAI-compatible `/responses` endpoint, and the platform manages conversation history, streaming, and session lifecycle. Prefer it for new hosted agents and generated plans.

A tool-using agent streams each tool call as output items, because evaluators score only output items; never return a bare `TextResponse` from it. With `azure-ai-agentserver-responses` 2.2.0–2.3.0 (check the installed API first), the `@app.response_handler` of `ResponsesAgentServerHost()` returns an async generator that creates `ResponseEventStream(response_id=context.response_id, request=request)`, yields `emit_created()` and `emit_in_progress()`, then the events of `output_item_function_call(name, call_id, arguments)` and `output_item_function_call_output(call_id, output)` for each call, then those of `output_item_message(text)`, kept last so `output_text` stays the answer, and finally `emit_completed()`.

Use the **invocations** protocol only when the user explicitly requests it, when an existing deployed agent already depends on it, or when a required sample/runtime is not yet available through Responses. If invocations is selected, document the reason in `./docs/spec.md` (SDD) or the root `README.md` (rapid).

## Python dependency contract (`requirements.txt`)

Declare each agent's dependencies in `requirements.txt` or `pyproject.toml`. Resolve the latest stable compatible releases at implementation time and lock them; the table is the required intent for the choices already made. Pick one framework row per agent, following SKILL.md's framework rule.

| When | Package | Why |
| --- | --- | --- |
| Always | `azure-identity` | `DefaultAzureCredential`: managed identity hosted, `az login` locally |
| Always | `azure-ai-agentserver-responses` | Serves the Responses endpoint; its core exports host telemetry from `APPLICATIONINSIGHTS_CONNECTION_STRING` |
| Invocations only | `azure-ai-agentserver-invocations` | Only when invocations is explicitly selected |
| Agents that use runtime skills | `github-copilot-sdk[telemetry]` | Copilot runtime, BYOK provider and runtime telemetry; brings `httpx` for the toolbox bridge in [`copilot-sdk-with-toolbox.py`](copilot-sdk-with-toolbox.py) |
| Basic agents and explicit workflows | `agent-framework-foundry` (add `agent-framework-foundry-hosting` when hosting through MAF) | Microsoft Agent Framework subpackages, each pinned with `==`; never the `agent-framework` meta-package |
| Multi-file skills or skills outside a toolbox | `azure-ai-projects` | Skills API download (see microsoft-foundry); toolbox skills arrive as MCP resources instead |
| In-process OpenAI-client model calls | `opentelemetry-instrumentation-openai-v2` | Model spans the runtime doesn't emit |

Don't add a second global telemetry exporter next to the hosting adapter's ([observability.md](observability.md)). Don't add `azure-search-documents`: Foundry IQ grounding comes through the toolbox; add Search SDKs only for the direct-retrieval escape hatch in [`foundry-iq-grounding.md`](foundry-iq-grounding.md#escape-hatch-direct-in-code-retrieval).

Resolve versions against the index the build uses as well, because a mirror or proxy can lag the official index. Hashed locks keep only sha256, sha384 or sha512 hashes; pip rejects others ("Allowed hash algorithms for --hash are sha256, sha384, sha512").

## Local runs and code packaging

- `azd ai agent run` syncs with `uv sync --locked`. If it reports that `uv.lock` needs updating while `pyproject.toml` and the lock agree, a machine uv config (`/etc/uv/uv.toml`, `~/.config/uv/uv.toml` or `UV_INDEX*`, often a package feed proxy) is rewriting the index. Re-lock only for the local run, then restore the committed lock before deploying.
- Code deploy packages the agent's service folder using only its `.agentignore`; `.azdignore` is ignored. The defaults already exclude `.env*`, `.azure/`, `.git/`, `.venv/`, `__pycache__/` and `*.pyc`, so list only the extra non-runtime files: tests, evaluators, eval config and the Dockerfile.

## Copilot SDK compatibility

Generated code must match the latest stable `github-copilot-sdk`, not a stale example. At implementation time, resolve the latest stable release from the official index, install it, and inspect `CopilotClient.create_session`, `CopilotSession.send_and_wait`, the event data types and the async context-manager lifecycle before writing handlers. If the build's index lacks that release, lock the newest stable release it serves (never a pre-release) and record the gap. [copilot-sdk-foundry.md](copilot-sdk-foundry.md) lists what to record.

Compatibility checks belong to the generated application's implementation and CI, which run against its resolved lockfile; this skill bundles no SDK test suite. If companion-skill guidance conflicts with the installed package, follow the package API and report the defect upstream (issue or PR) instead of patching the third-party skill locally.

When reviewing or correcting SDK code, state the resolved version, the Python minimum (3.11 for v1.0.14–1.0.23; hosted agents keep 3.13), and the session-creation, prompt-send, event and lifecycle shapes, so the correction can be checked.

## Read-only container filesystem

Hosted containers are read-only except `/tmp`. Default every runtime write (skills, session state, generated files) under `tempfile.gettempdir()`; writing under the app directory crashes the first invocation. The reference agent writes skills to a per-turn temporary directory and moves Copilot session state under the temp directory only when HOME isn't writable.
foundry-iq-grounding.md 6.8 KB
# Foundry IQ grounding

Reference for the `foundry-agentic-loop` skill: how a GitHub Copilot SDK **hosted agent** grounds enterprise answers through a **Foundry IQ** knowledge base by consuming a governed Foundry **toolbox MCP endpoint**. `foundry-agentic-loop` decides *that* grounding is Foundry IQ; this file holds the access path, identity, refusal, validation, and escape-hatch guidance. Defer index/knowledge-base provisioning and role selection to `microsoft-foundry` and its `rbac` sub-skill.

## Primary pattern: hosted agent + toolbox MCP

Default foundry-agentic-loop grounding uses:

1. **GitHub Copilot SDK hosted agent** running on Foundry hosted agents and exposing the Responses API by default.
2. **Foundry Skills API** for behavioral instructions; the agent downloads governed skill versions into a writable temp directory at runtime.
3. One **Foundry IQ knowledge base** exposed through a Foundry toolbox connection/tool, typically a `CognitiveSearch` or Foundry IQ grounding connection backed by Azure AI Search.
4. One governed **Foundry toolbox MCP endpoint** as the only runtime tool and grounding surface the agent calls.

The hosted agent should not import `azure-search-documents`, instantiate Search clients, or call Foundry IQ retrieval APIs by default. It bridges the toolbox MCP endpoint, lets the toolbox broker grounding/tool identity, and treats the toolbox response as the source of answer evidence and citations. Direct Search or Foundry IQ calls belong only in provisioning, ingestion, or the explicitly documented diagnostic escape hatch below.

## No-bypass rule

Every enterprise answer flows through the toolbox-hosted Foundry IQ grounding tool. The app and agent must not issue ad hoc Azure AI Search queries that sidestep the knowledge base, toolbox governance, or citation contract. Direct in-code retrieval belongs only in the [escape hatch](#escape-hatch-direct-in-code-retrieval).

## Grounding identity

The primary toolbox path is brokered:

| Retrieval path | Authenticates as | Grant needed |
| --- | --- | --- |
| **Toolbox MCP grounding tool** - a Foundry IQ / `CognitiveSearch` connection attached to the toolbox | Hosted-agent **agent identity** (`agentIdentityId`) via Agent Service-brokered tool identity | Search / knowledge-base data-plane role on `agentIdentityId`; repeat after publish because agent identity can change |
| **Direct in-code retrieval escape hatch** - agent code calls Search / Foundry IQ APIs with `DefaultAzureCredential` | Hosted-agent **runtime instance managed identity** | Search Index Data Reader on the Search service, granted in `postdeploy` after the runtime identity exists |

Generated plans should make the brokered toolbox/tool identity path the default. Runtime instance managed identity Search Reader is not part of the baseline; add it only when direct retrieval is explicitly selected for troubleshooting or unsupported-tool scenarios.

The connection's auth mode decides who calls Search: a `ProjectManagedIdentity` connection calls as the project's managed identity (one validated build needed Search Index Data Reader plus Search Service Contributor on it). When proving least privilege by removing a role, wait past the connection's token cache before trusting continued access.

## Citations and refusal

Return source document, section, and anchor/chunk id for every grounded claim. Rebuild each citation (title, section, anchor, non-routable source URI) from a retrieved document that survived filtering; never pass through provider Search URLs or citation fields the model wrote. Treat "answer with zero citations" as a refusal in the API contract.

Refusal must be deterministic. Prefer a structural signal from the grounding tool - no citations survived retrieval / reranking - rather than string-matching model prose or trusting a model-reported refusal flag. Probe raw retrieval with one supported and one unsupported query first: a toolbox Search tool can return low-scoring documents instead of an empty list. If the toolbox exposes a reranker or relevance threshold, keep it environment-configurable per corpus and apply it before synthesis so weak matches become empty evidence. Otherwise filter the tool's structured documents by an environment-configured minimum score in the agent, reject malformed scores, and refuse when none survive.

## Runtime validation

Post-deploy validation must invoke the **deployed** hosted agent and cover:

1. **Known answer** - a supported question returns the expected grounded claim.
2. **Citation correctness** - every supported claim cites the expected source, section, and anchor/chunk.
3. **Freshness** - newly ingested or updated source content becomes retrievable within the documented ingestion window.
4. **No-supported-source refusal** - an unsupported question returns the exact deterministic refusal with no fabricated citation.
5. **Retrieval telemetry** - logs/traces show the toolbox grounding call, result/citation counts, latency, and refusal reason; runtime logs show no direct Search client calls.

If a known-answer query refuses with empty citations, inspect the toolbox call result and agent logs for brokered identity, role assignment, ingestion, or retrieval failures before tuning prompts.

## Escape hatch: direct in-code retrieval

Use direct in-code Search / Foundry IQ retrieval only when the toolbox path cannot support a required diagnostic or unsupported preview capability. Record it in `docs/spec.md` (SDD) or the root `README.md` (rapid), isolate it from the default agent runtime, and remove or disable it after the diagnostic is complete.

Escape-hatch implications:

- Add the direct retrieval SDK dependency only in that variant; do not include `azure-search-documents` in default hosted-agent dependencies.
- The call authenticates as the hosted-agent **runtime instance managed identity**, not `agentIdentityId`.
- Grant **Search Index Data Reader** to the runtime instance identity in a reproducible `postdeploy` hook because Bicep cannot assign a role to an identity that does not exist until the agent is deployed.
- Validate both auth paths if the app also runs direct retrieval in-process; the backend app identity and hosted-agent runtime identity need separate Search access.

Common direct-retrieval APIs include `KnowledgeAgentRetrievalClient` and `SearchIndexKnowledgeSourceParams`. Keep examples and troubleshooting for those APIs in this escape-hatch section so they are not mistaken for the primary architecture.

## Source

- [Use skills with Microsoft Foundry agents (preview) - azd](https://learn.microsoft.com/en-us/azure/foundry/agents/how-to/tools/skills?pivots=azd#manage-skills-with-the-rest-api)
- [Curate intent-based toolbox in Foundry (preview)](https://learn.microsoft.com/en-us/azure/foundry/agents/how-to/tools/toolbox)
- [Foundry hosted agents](https://learn.microsoft.com/en-us/azure/ai-foundry/agents/concepts/hosted-agents?view=foundry)
foundry-models.md 5.2 KB
# Foundry models selector

Choose the model, version, SKU, capacity and region for each deployment the solution needs. SDD declares the deployments in `azure.yaml` under `services.ai-project.deployments[]` ([azd-layout.md](azd-layout.md#azureyaml)) and `azd provision` creates them. Rapid reuses the project's deployments and asks before adding one. Both record the selection in `.azure/deployment-plan.md`. Resolve live quota, availability and provisioning commands through `microsoft-foundry`.

> The catalog changes monthly. Resolve exact versions, SKUs, registration and regional availability live through `microsoft-foundry` and the [Azure-direct models](https://learn.microsoft.com/en-us/azure/foundry/foundry-models/concepts/models-sold-directly-by-azure) and [region availability](https://learn.microsoft.com/en-us/azure/foundry/foundry-models/concepts/models-sold-directly-by-azure-region-availability) pages; never copy a version from memory.

## Starting points by task

Recommend the first fit, then offer alternatives only when cost, region, quota or registration blocks it. Prefer GA for production and flag Preview or registration-required models before deploying.

| Task | Start with | Consider when needed |
| --- | --- | --- |
| Chat, agents, tools | `gpt-5.4-mini` (SDD default) | a nano tier for cost; a flagship tier for hard reasoning or very long context |
| Deep reasoning | the current GPT flagship | an o-series mini for cost |
| Coding | the current Codex model | `gpt-4.1` for very large contexts |
| Multimodal input | `gpt-5.4-mini` | the flagship for long context |
| Embeddings | `text-embedding-3-large` | `text-embedding-3-small` for cost |
| Rerank | Cohere rerank (current version) | its fast tier for latency |
| Image, audio, video, document AI | the current GA model in that family | Preview models only with approval |
| Cost-optimized routing | `model-router` | only where it is offered (few regions) |

## Joint region and capacity preflight

Treat placement as one subscription-specific decision, not a static model lookup. Before persisting `AZURE_LOCATION` or declaring a deployment, validate every required resource in each candidate region:

| Resource | Validate live |
| --- | --- |
| Foundry model | Exact model, version, SKU, requested capacity/quota, and registration status |
| Azure AI Search | Required SKU availability and regional feature support |
| Foundry hosted agents | Hosted-agent availability for the target project/account shape |
| Preview dependencies | Required provider/feature registration and regional availability |

Start with the preferred region, then use the target subscription's live availability and quota checks through the maintained `microsoft-foundry` guidance. If any required resource fails, reject that candidate and rank alternatives that satisfy the **complete** resource set; do not move one resource independently unless the architecture explicitly supports cross-region placement.

Write the placement decision to `./.azure/deployment-plan.md`:

| Field | Value |
| --- | --- |
| Preferred location | User/data-residency preference |
| Deployed location | First candidate that passed the joint preflight |
| Evidence | Model/version/SKU/capacity, Search SKU, hosted-agent, and preview checks |
| Variance | Reason deployed location differs, or `none` |

When the deployed location differs from the preferred location, update `./docs/spec.md` (SDD) before implementation continues.

## Record the selection

Only after the joint preflight passes:

- Set the region: `azd env set AZURE_LOCATION "<region>"` (SDD).
- Declare each deployment in `azure.yaml` `services.ai-project.deployments[]` with its deployment `name`, model `name`, `format` (`OpenAI`, `Microsoft`, `MistralAI`, `Cohere`, `DeepSeek`, `Meta`, `xAI`, ...), `version`, and `sku` `name` (usually `GlobalStandard`) and `capacity` (thousands of tokens per minute).
- Record the preferred and deployed locations, each deployment and the evidence in `.azure/deployment-plan.md`.

## Workflow

1. Take the task and modality (chat, reasoning, coding, multimodal, embeddings, rerank, image generation, video, audio, document AI) from the spec or brief; ask only when neither states it.
2. Recommend the starting point for the task and resolve its current GA version live.
3. Confirm the preferred region. Start with `eastus2` (broadest Azure OpenAI coverage); prefer `swedencentral` for EU data residency.
4. Confirm capacity. Defaults: **100** (chat / reasoning / coding), **30** (embeddings), **50** (image / audio). When one end-to-end request makes several model calls, size chat capacity to at least four times its estimated tokens, within the remaining quota, so Verify can run E2E cases in parallel. GlobalStandard bills per token, so the headroom costs nothing; record the sizing in the deployment plan.
5. Flag any **registration-required** or **Preview** models explicitly before deploying.
6. Run the joint live preflight for the model and every co-located required service; rank only complete placements.
7. [Record the selection](#record-the-selection).
8. **Reconcile actual availability.** If provisioning selects a different model or location, update `./docs/spec.md` and `./.azure/deployment-plan.md` immediately.
foundry-toolbox.md 5.5 KB
# Foundry toolbox

Reference for the `foundry-agentic-loop` skill: how a solution's skills, MCP tools and grounding reach its hosted agents through one Foundry toolbox. `microsoft-foundry` owns the command surface and tool types (its toolbox guide), [azd-layout.md](azd-layout.md#azureyaml) owns the declarative services, and [copilot-sdk-with-toolbox.py](copilot-sdk-with-toolbox.py) is the reference consumer.

## Model

- A **toolbox** bundles project connections, skills and tools behind one MCP endpoint. Versions are immutable: every change creates one, and only the first becomes the default automatically.
- A **skill** is a `SKILL.md` (front matter with `name` and `description`, then Markdown instructions) versioned in the project. Skills are in preview.
- The **consumer** URL `<project>/toolboxes/<name>/mcp?api-version=v1` always serves the default version, so promoting a toolbox version reaches agents without a redeploy. The **developer** URL `.../toolboxes/<name>/versions/<v>/mcp?api-version=v1` pins one version.
- Attached skills arrive as MCP resources (`skill://<name>/SKILL.md`) that follow the skill's default version unless the toolbox pins `version`. The agent writes them under the temp directory per request, because hosted containers are read-only except `/tmp`; the agent image never copies `skills/`.

## Author

1. Write each skill at `skills/<name>/SKILL.md`; its front matter `name` matches the folder.
2. Build or reuse each MCP server (FastMCP over streamable HTTP, generated with `python-mcp-server-generator` from [build-skills-catalog.md](build-skills-catalog.md)). Reach servers through connections, never hard-coded URLs or secrets. Expose Foundry IQ grounding through the toolbox too ([foundry-iq-grounding.md](foundry-iq-grounding.md)).
3. Compose one toolbox per capability set: `skills[]`, `connections[]` (connections must already exist), and connectionless built-ins such as `web_search` or `code_interpreter` under `tools[]`. At most one tool may be unnamed: name built-ins with `name` and MCP tools with `server_label`. Before exceeding about five tools, add `toolbox_search_preview`, which counts as the unnamed tool.
4. Agents that load skills run on the Copilot SDK and consume the toolbox like the reference agent. MAF agents follow microsoft-foundry's toolbox-in-hosted-agent guidance.

## Publish

- **SDD:** declare `azure.ai.skill`, `azure.ai.connection` and `azure.ai.toolbox` services ([azd-layout.md](azd-layout.md#azureyaml)). Deploy publishes them in `uses` order and writes `TOOLBOX_<NAME>_MCP_ENDPOINT`; map it to the agent's `TOOLBOX_ENDPOINT`. Without approval to upgrade older extensions, use the ordered `postprovision` fallback in the same file.
- **Rapid:** publish with the CLI against the selected project (`azd ai project set <project-endpoint>`):

  ```bash
  azd ai skill create claims-policy --file skills/claims-policy/SKILL.md --no-prompt   # later versions: azd ai skill update
  azd ai toolbox create claims-tools --from-file toolbox.yaml --no-prompt              # writes TOOLBOX_CLAIMS_TOOLS_MCP_ENDPOINT
  ```

  ```yaml
  # toolbox.yaml
  description: Claims tools
  skills:
    - name: claims-policy          # omit version to follow the skill's default
  connections:
    - name: claims-mcp-conn        # RemoteTool (MCP)
    - name: policy-search          # CognitiveSearch needs index
      index: policies
  tools:
    - type: web_search
      name: web
  ```

- **Change:** `azd ai toolbox connection add|remove` and `azd ai toolbox skill add|remove` each create a version without changing the default; promote or roll back with `azd ai toolbox publish <name> <version>`. Connectionless built-ins can't be added later: recreate the toolbox with the full set. `azd ai skill update <name> --set-default-version <v>` rolls a skill without uploading content.
- **Extensions:** `azure.ai.toolboxes`, `azure.ai.skills` and `azure.ai.connections`, at the minimum versions in [azd-layout.md](azd-layout.md#azureyaml).

## Consume

Follow [copilot-sdk-foundry.md](copilot-sdk-foundry.md) and the reference agent:

- Keep the URL in `TOOLBOX_ENDPOINT`, never a `FOUNDRY_*` name, which the platform overwrites. If the written URL pins `/versions/<v>/`, redeploy the agents that use the toolbox after it changes; record which form each agent uses.
- Send a token for `https://ai.azure.com/.default` on every request (cognitiveservices tokens get 401), `Foundry-Features: Toolboxes=V1Preview`, and the caller's `x-agent-foundry-call-id` when present.
- `initialize` is optional; `prompts/list` and `ping` are unsupported. MCP-sourced tools are named `<server_label>___<tool>`.
- The proxy does not enforce `require_approval`: approve tools in the agent's permission handler.
- A `-32006` error wrapping `CONSENT_REQUIRED` carries a per-user consent URL for an OAuth connection: surface it to the caller instead of retrying.
- An HTTP 403 from the toolbox means the caller lacks Foundry User on the project; a `-32007` error wrapping 403 comes from the MCP server's own auth.

## Verify

- `tools/list` returns the expected tools and `resources/list` the expected `skill://` entries.
- Hosted logs show skills written under the temp directory, and answers show each skill applied.
- Record the toolbox name, its published default version and the URL form in the root `README.md` (rapid) or `docs/implementation.md` (SDD).

Sources: microsoft-foundry toolbox and skills guides; [Toolbox](https://learn.microsoft.com/azure/foundry/agents/how-to/tools/toolbox); [Skills](https://learn.microsoft.com/azure/foundry/agents/how-to/tools/skills).
hosted-integration-checkpoint.md 13.4 KB
# Hosted integration checkpoint

Read for architecture, the first hosted deployment, and changed identity/endpoint integrations. Prove the hosted boundary before expanding orchestration or implementing the full application. This is an acceptance gate, not a replacement for `microsoft-foundry` platform workflows.

## Endpoint contract

Record these distinct values in the root `README.md` (rapid) or `docs/implementation.md` (SDD) and persist discovered values in the applicable deployment configuration and Git-ignored `.env`. Record their source, authentication audience, consuming component and version. Unknown values remain pending until discovery; do not synthesize endpoints from display names.

| Application variable | Meaning and validation |
| --- | --- |
| `APP_FOUNDRY_PROJECT_ENDPOINT` | Full project URL including `/api/projects/<project>`, returned by project discovery. Used by project clients. |
| `MODEL_API_BASE_URL` | Actual model-hosting account's OpenAI-compatible base ending in `/openai/v1/`. Used by the model provider; it is not the project or hosted-agent URL. Record model deployment name separately. |
| `HOSTED_RESPONSES_ENDPOINT` | Deployed agent's actual Responses request URL, including required API version and agent routing. Record the agent version used by the probe; distinguish this complete request URL from an SDK base URL that appends `/responses`. |
| `TOOLBOX_ENDPOINT` | Toolbox MCP URL, including `api-version=v1`, mapped from the azd-written `TOOLBOX_<NAME>_MCP_ENDPOINT`. Record the toolbox name, its published default version and whether the URL is the consumer form (follows the default) or pins `/versions/<v>/`. |

Keep `FOUNDRY_PROJECT` as the project **ARM ID**, not an endpoint. Keep platform-owned `FOUNDRY_*` variables untouched. A reported build had its custom `FOUNDRY_PROJECT_ENDPOINT` overwritten with an account-only URL; use `APP_FOUNDRY_PROJECT_ENDPOINT` for the application's verified full URL, explicitly pass it to project clients, and validate its path at startup. Do not silently append guessed project names or fall back to the reserved value. Verify how current adapters consume platform configuration through `microsoft-foundry`.

## Minimal deployment and identity

1. Reuse the Basic sample, agreed framework and model deployment. Implement one deterministic, read-only probe that always requires a model response, plus one toolbox skill load when the architecture uses runtime skills and one MCP tool call when it uses MCP tools; the response uses their results. Never add an unused skill or tool to satisfy the checkpoint. Keep full UI, backend and multi-agent orchestration out of this slice. Record each excluded capability as `N/A` with its reason; mocks or skipped checks cannot pass a required boundary.
2. Deploy only the necessary MCP dependency and toolbox skill/version, if any, then code-deploy the agent. Confirm approval for billable operations. Provisioning or `active` only enables the probe; it does not pass it.
3. Discover the deployed agent's **actual principal/object ID** from deployment/identity metadata (`azd ai agent show <agent> --output json`: `instance_identity` takes Azure roles; the `blueprint` takes none, and its client ID only joins MCP Easy Auth allow-lists). A new principal cannot be checked before creation. Distinguish object ID from client/application ID and the agent resource ID. Record tenant, agent/version, principal, resource scope and required operation/role.
4. Verify effective grants (including inheritance/conditions) and actual data-plane access. Use the following reported-build combinations as checks, not unconditional grants to every solution. Resolve current roles and least-privilege scope through `microsoft-foundry`.

| Principal | Resource scope | Role to verify when this path requires it |
| --- | --- | --- |
| Runtime instance identity | Foundry project | Foundry User for explicit project/toolbox access, including runtime skill download (without it the hosted invoke returns 500); account for platform-provided access and current role definitions. |
| Runtime instance identity | Account actually hosting the model | Cognitive Services OpenAI User for direct account-level OpenAI inference. Project access alone does not establish this. |
| Identity directly emitting authenticated Application Insights telemetry | Application Insights component | Monitoring Metrics Publisher. Verify the runtime instance identity when the agent is the emitter; do not substitute the deployer's grant. |
| Collector identity for native Azure Monitor OTLP ingestion, when used | Destination Data Collection Rule (DCR) | Monitoring Metrics Publisher. Verify the collector's actual principal, which can differ from the agent; do not add this route or grant when unused. |

Keep the deployer, project managed identity, agent identity, runtime caller and **toolbox connection identity** separate. Agent-to-toolbox access and connection-to-downstream MCP/service access are different checks. Confirm the configured connection auth mode and its principal/resource permissions; an agent grant cannot repair the wrong downstream identity.

Invoke the deployed endpoint with an authorized caller, but ensure downstream model/toolbox operations use the hosted workload credential and platform caller context. A developer token can authorize the external probe; it must not replace the agent's internal credential. No copied `az login` tokens or secret-key fallback to make the checkpoint pass.

## Probes and pass criteria

- Run a minimal direct model Responses request and toolbox skill/tool probe **inside the hosted identity/context path**, then run the equivalent SDK-mediated agent request. Record the actual skill version loaded and MCP tool name/call result using SDK/tool events or safe correlated telemetry, not the model's claim that it used them. A local run proves readiness and skill load only: `AgenticIdentityToken` tool calls fail outside the host ("requires AgentInstanceClientId and AgentBlueprintClientId").
- Toolbox MCP calls can appear as `<server>___<tool>` in Responses output: parse the server prefix and require the exact tool name. Check the toolbox version the agent uses: read back the published default version (`azd ai toolbox show <name>`) or, for a pinned URL, the version in its path, and require the expected tools and skills there.
- Exercise JSON and SSE using the actual returned content type. For SSE, consume through `response.completed`; EOF, `[DONE]`, text deltas, `session.idle` or a stopped spinner alone are insufficient. For nonstreaming JSON, require a final response object with `status: "completed"`; queued/in-progress responses require bounded polling. Also prove the streaming terminal event when streaming is supported.
- Treat `response.failed`, `response.incomplete`, cancellation, timeout, protocol errors and embedded error payloads as failures, even with HTTP 200 or CLI exit code zero. A CLI wrapper must parse the response and return failure for unsuccessful terminal status.
- Require nonempty, schema-valid application output with expected probe values and evidence of every required skill/tool/model operation. Reject absent upstream fields explicitly; do not turn missing results into empty success.
- Correlate application request ID, response ID, hosted session ID, SDK session/turn ID, agent version and service request IDs. Save a concise checkpoint record and evidence locations in the same file as the endpoint contract. Missing evidence leaves the gate blocked; label unavailable IDs as such, never invent them.
- Require the deployed probe's hosting-request, model-request and required tool-execution spans to arrive in the configured telemetry destination, without enabling sensitive prompt/completion/tool-content capture. Verify trace/parent relationships and agent/version identification using the destination's actual schema. For Copilot SDK, configure both producers through the [telemetry recipe](copilot-sdk-foundry.md#telemetry). A project connection, exporter startup message or hosting-request span alone is insufficient. Allow bounded ingestion delay; missing required spans leave the checkpoint incomplete. Only after the required checks pass may full application work begin.

## Diagnostic decision tree

| Failure | Next bounded action |
| --- | --- |
| Import, startup or dependency resolution | Capture exact Python, SDK, hosting adapter and running Copilot runtime versions. Check installed signatures and package/runtime compatibility. For remote-resolution failures use the conditional [packaging fallback](copilot-sdk-foundry.md#dependency-packaging-fallback), not a framework rewrite. |
| 401 | Compare endpoint/base path, expected token audience, refresh callback and forwarded platform context for direct versus SDK requests **under the same deployed identity**. Log no tokens or caller-context header values. |
| 403 | Check actual principal/resource/role combinations and toolbox downstream identity separately. After a confirmed role change, retry the minimal probe with backoff and a fixed deadline (for example five attempts within five minutes). Refresh credentials through the supported provider; do not repeatedly redeploy identical code. |
| Developer probe passes, hosted probe fails | Compare the actual identities, network access, full project URL, model account and platform caller context. Developer success is not hosted proof. Do not disable network isolation to bypass a failure. |
| Direct hosted request passes, SDK fails | Compare sanitized method, route, deployment name, API version, audience, header **names**, content type and payload schema. Check adapter/SDK/runtime signatures before changing RBAC. |
| HTTP success but failed/missing output | Inspect response ID, final status, structured error and matching service request IDs. Parse JSON/SSE correctly; never reinterpret transport success as agent success. |
| Intermittent failures under load | Check request-local context, response-ID matching, session isolation, token refresh, cancellation and atomic tool-budget reservation before async work. |
| Missing or host-only telemetry | Check host and runtime producer configuration separately, active trace context, receiver/export route, destination/schema, actual exporter identity permissions, sampling and lifecycle flush. Allow bounded ingestion delay; do not pass the gate or repeatedly redeploy unchanged code. |
| Transient `postdeploy` failure after a successful deploy | Rerun only the idempotent hook (`azd hooks run postdeploy`) and its read-back checks; do not redeploy unchanged code. |

Log safe structured diagnostics: application correlation ID, response ID, hosted and SDK session IDs, agent name/version, available service request IDs, SDK/runtime versions, status/error code and sanitized error summary. Capture response headers such as `x-agent-session-id` on failures too. Exclude Authorization, cookies, tokens, opaque caller-context values, `.env` dumps and sensitive bodies.

Retry only transient failures within a declared attempt/deadline budget; do not blindly replay non-idempotent tool calls. Redeploy only for changed code, dependencies or deployment configuration. Track debug processes and hosted/SDK sessions created by this task; stop only those temporary resources afterward. Preserve the user's sessions and the local app servers required by the acceptance handoff.

## Contract tests

Add targeted tests before expanding each boundary, then run the applicable full-app cases at local acceptance:

- Missing/null upstream IDs, output, tool results or schema fields produce explicit errors.
- Responses text comes from the final `message` output item: the top-level `output_text` can be null when tool items precede it. Omit `previous_response_id` on a first turn; null returns HTTP 400.
- JSON and SSE success, embedded errors, incomplete status, truncated streams and timeouts produce correct terminal state and error rendering. When the API emits only a terminal SSE event, call the agent without upstream streaming, which can take a different model path, and test that JSON and SSE return the same validated result.
- Concurrent/interleaved requests map events and results to their own response/request/session IDs; a late result cannot resolve another request or overwrite its persisted state.
- Reserve tool-call limits atomically **before** dispatch/await; simultaneous calls cannot exceed the cap. Test the boundary and rejected calls, including failure/cancellation accounting.
- Token expiry/refresh and per-request context reach both model and toolbox without cross-user/session leakage.
- Concurrent hosted requests retain separate trace/parent associations through runtime and tool callbacks. Check content-capture defaults, graceful flush and explicit export failures; local mocks do not replace deployed span-ingestion evidence.
- App failures render clearly; retry, persistence/reload and export preserve validated results and failure state without secrets. Exercise mobile layout and keyboard navigation/focus as well as the happy path.

## Platform sources

Resolve commands and changing platform contracts through the installed `microsoft-foundry` skill. References checked on 2026-09-22:

- [Hosted agent permissions](https://learn.microsoft.com/azure/foundry/agents/concepts/hosted-agent-permissions)
- [Hosted runtime contract](https://learn.microsoft.com/azure/foundry/agents/concepts/hosted-agent-contract)
- [Toolbox authentication and hosted integration](https://learn.microsoft.com/azure/foundry/agents/how-to/tools/use-toolbox-hosted-agent)
- [Source-code deployment](https://learn.microsoft.com/azure/foundry/agents/how-to/deploy-hosted-agent-code)
implement.md 5.9 KB
# Implement phase

Build what `docs/spec.md` specifies on the target in `.azure/deployment-plan.md`. Apply the [skill defaults](../SKILL.md#defaults) and use `microsoft-foundry` for platform operations. Reconcile existing code and infra; never re-scaffold over work.

Run azd from the workspace root, with `AZURE_DEV_USER_AGENT=microsoft_foundry_skill` inline on each azd command.

## 1. Scaffold

Skip any step whose result already exists.

1. Take the Basic sample's `manifestUrl` from `azd ai agent sample list --language python --output json` (the recommended Basic entry).
2. Scaffold the first agent as in [scaffold into an existing workspace](azd-layout.md#scaffold-into-an-existing-workspace): `azd ai agent init .` with `--no-prompt` in an empty `.scaffold` folder, then move it into place. Never run `azd init -t` first: agent init would rewrite the provider and nest the project.
3. Rename its service key to `<agent>`, point its `project` at `src/agents/<agent>`, and set the top-level `name` to the solution. For each further agent, copy a working agent folder to `src/agents/<name>` and run `azd ai agent init --src ./src/agents/<name> --agent-name <name> --no-prompt --deploy-mode code --runtime python_3_13 --entry-point main.py`.
4. `azd env set` each deployment-plan variable, one per command, with `AZURE_RESOURCE_GROUP` first. Read them back with `azd env get-values`.
5. Sanity-check `azure.yaml`:
   - `services.ai-project.deployments[]` is not empty.
   - There is no literal `{{…}}`.
   - Every `entryPoint` exists.
   - There is no duplicated `-2` agent service.

## 2. Infra and services

Lay out `azure.yaml`, `infra/foundry` and `infra/app` exactly as in [azd-layout.md](azd-layout.md):

- **Layers:** a Foundry layer, then a Bicep app layer.
- **Declarative services:** skills, MCP connections and the toolbox.
- **Apps:** Container Apps with `remoteBuild`.
- **Identity:** every row of the RBAC contract, plus a `postdeploy` hook for the runtime instance rows and MCP allow-lists ([grants after deploy](azd-layout.md#grants-after-deploy)).

Validate with `az bicep build --file infra/app/main.bicep`. Then run `azd provision --no-prompt`. Outside a workflow run, whose spec approval covers it, ask first, naming the checkpoint services this phase also deploys. Record the actual regions and resource groups, including the Foundry provider's group (`azd env get-value AZURE_FOUNDRY_RESOURCE_GROUP`), in the plan's Region, Resource groups and Environment variables rows, and any fallback with its reason in the plan and `docs/spec.md`, before continuing. Upsert `FOUNDRY_PROJECT` (the `AZURE_AI_PROJECT_ID` value) into the root `.env`. For Copilot SDK agents, discover the model account's `/openai/v1/` base and `azd env set MODEL_API_BASE_URL <url>` ([endpoint contract](hosted-integration-checkpoint.md#endpoint-contract)).

## 3. Build

1. **Contract first.** Code against the frozen contract in `docs/spec.md`. Contract changes go to the spec first.
2. **Integration checkpoint.** Pass the [hosted integration checkpoint](hosted-integration-checkpoint.md) before fan-out. Build a minimal agent that proves a model request, plus one toolbox skill load and one safe MCP tool call when the spec requires them; record excluded ones as `N/A`.
   1. Prove readiness and skill load locally with `azd ai agent run --no-client`, in the background, and `azd ai agent invoke --local "<probe>"`. `AgenticIdentityToken` tool calls work only hosted.
   2. Run `azd deploy <service>` for the MCP server, skill, connection, toolbox and agent services, in `uses` order.
   3. Prove the hosted version with `azd ai agent invoke <agent> "<probe>"`.
3. **Workstreams.** Build the spec workstreams in parallel when subagents are available. Each worker owns exclusive workspace-relative files or folders, runs its acceptance checks and reports needed changes elsewhere as issues. Shared files stay with the lead: `azure.yaml`, `infra/`, `docs/`, `.env`, `.azure/`, `.agentic-loop/`, `AGENTS.md` and the root lockfiles. After the workers finish, the workflow diffs `git status` against its pre-fan-out snapshot and hands any changed path outside the workstreams to integration as an issue.
4. **Integration.** Integrate centrally. Run builds, linters and unit tests, and lock Python dependencies (`uv.lock` or pinned versions).

**Deployments.** Implement deploys only the checkpoint services (MCP servers, skills, connections, toolbox and agents); the frontend, backend and workers run locally until Deploy. Reproduce agent defects locally first (`azd ai agent run` with `invoke --local`), and redeploy a hosted agent only for hosted-only behavior, once per verified fix. Redeploy only services whose source or configuration changed since their last verified deployment. After a transient `postdeploy` failure, rerun only the hook with `azd hooks run postdeploy`.

Agent code follows these references:

- [foundry-hosted-agent.md](foundry-hosted-agent.md)
- [copilot-sdk-foundry.md](copilot-sdk-foundry.md) or `microsoft-agent-framework`
- [foundry-toolbox.md](foundry-toolbox.md)
- [foundry-iq-grounding.md](foundry-iq-grounding.md)
- [observability.md](observability.md)

## 4. Record

Write `docs/implementation.md` with:

- the components and their files;
- an animated Mermaid flow of a request across the frontend, backend, agent, toolbox, model and telemetry;
- the env contract with the discovered endpoint values ([endpoint contract](hosted-integration-checkpoint.md#endpoint-contract));
- the checkpoint record and its evidence locations;
- how to run each component locally;
- deviations from the spec, with their reason.

Add microsoft-foundry's `AGENTS.md` marker (its quick-start Step 6) if missing, outside the foundry-agentic-loop markers.

## Gate

Pass only when:

- provisioning succeeded;
- the checkpoint has evidence;
- builds and unit tests pass;
- the backend calls the agent through its dedicated endpoint (`azd ai agent show`) with scope `https://ai.azure.com/.default`.

Report: status, summary, artifacts, assumptions, issues and lessons.
implementation-contract.md 3.7 KB
# Cross-component implementation contract

Reference for the `foundry-agentic-loop` skill: the small contract that must be frozen before frontend, backend, agent, ingestion, or infrastructure work proceeds in parallel. Copy this table into the root `README.md` (rapid) or the `Implementation contract` section of `./docs/spec.md` (SDD) and replace every placeholder.

## Contract table

| Contract | Frozen value | Producer / authority | Consumers | Verification |
| --- | --- | --- | --- | --- |
| `azure.yaml` service names | `<frontend>`, `<backend>`, `<agent>`, `<ingestion>` as applicable | Infrastructure | azd hooks, deployment scripts, CI | `azd config list` and manifest review |
| Environment variables | Exact name, type, required/optional status, and default for each variable | Provisioning output or owning service | Every component that reads it | Generated env map matches code/config reads |
| Hosted-agent protocol | Responses API version and OpenAI-compatible `/responses` endpoint | Foundry hosted agent | Backend/client | Contract test invokes deployed endpoint |
| Responses metadata | Allowed keys and JSON value types; no implementation-specific objects | Backend/client contract | Agent and telemetry | Schema validation |
| Toolbox endpoint | `<project-endpoint>/toolboxes/<name>/versions/<version>/mcp?api-version=v1`; define pinned versus promoted-version behavior | `azd ai toolbox create` / provisioning | Agent MCP bridge | MCP initialize and `tools/list` |
| MCP tools | Exact tool names, input JSON schemas, output/error shapes | Tool owners | Agent | Schema snapshot and discovery test |
| Model inference | Endpoint, deployment name, model/version/SKU, and token scope (`https://ai.azure.com/.default`) | Foundry provisioning | Agent framework | Authenticated smoke test |
| Response body | Exact JSON shape, status/error mapping, and streaming behavior | Backend API | Frontend/client | API contract test |
| Citations | Source, section, anchor/chunk id, and claim association | Foundry IQ/toolbox | Agent, backend, frontend | Known-answer citation test |
| Grounding refusal | Exact deterministic refusal text used when no cited evidence supports the answer | Product/API contract | Agent, backend, evals | No-supported-source test |
| Runtime versions | Python, Node, hosted-agent runtime and each direct dependency, including `github-copilot-sdk`, resolved during implementation to the latest stable release, API-verified before generating code and pinned exactly; exact image tags (digest preferred), never a floating "latest" | Official package index, the build's package index and registries | All services and CI | Lockfile/manifests match CI; the build's index or registry serves each pinned version |

For environment variables, add one row per value when that is clearer than a comma-separated list. Record both the producer and every consumer; this catches values that provisioning emits under one name while runtime code expects another.

## Reconciliation before merge

1. Compare every `azure.yaml` service and hook target with the frozen service names.
2. Search code, Bicep outputs, azd hooks, CI, and docs for each environment-variable producer and consumer.
3. Exercise the Responses endpoint with contract-valid metadata and validate response/citation/refusal schemas.
4. Initialize the toolbox endpoint, compare discovered MCP names and schemas with the frozen snapshot, and fail on drift.
5. Confirm model endpoint, deployment name, and token scope agree across provisioning and agent configuration.
6. Compare runtime and package manifests with the resolved version row and run compatibility checks in the generated application.
7. Update the contract and all consumers in one change when an intentional interface change is required.
improve.md 5.0 KB
# Improve mode

Recursive improvement: learn from past executions and refine the Agentic Loop skill and workflow with the smallest evidence-backed changes. Analysis is read-only; nothing is applied without approval.

## 1. Gather evidence

**Scope.** In a solution repository, use its own evidence. In a clone of `github/awesome-copilot`, the evidence lives in solution folders: find recent sessions that loaded `foundry-agentic-loop` with `session_store_sql`, confirm the folders with the user, and read their records.

**Budget.** Present proposals within about 20 minutes. Start from the distilled records below. Use session history only to confirm or quantify a candidate cluster, and never read raw transcripts (`events.jsonl`) end to end.

- **Flight records:** `.agentic-loop/runs/*.json`, with phases, rounds, gate status, issues, lessons, durations and outcome.
- **Lessons:** `docs/LOOP.md` entries and their status.
- **Workflow history:** `dynamic_workflows_manage` with `runs`, filtered to `foundry-agentic-loop-workflow`, then `inspect-run` for each failed, blocked or slow run.
- **Session history:** `session_store_sql` for recent Agentic Loop sessions in scope: failed tools, retries, user corrections, questions asked and manual fixes after a blocked pause. Time-bound every query and use `LIMIT`.
- **Current sources:** the `foundry-agentic-loop` skill (`SKILL.md`, `references/`, `assets/` and `evals/evals.json`) and the workflow `lib/*.mjs`.

## 2. Analyze

Cluster findings by root cause, not symptom. Look for:
- recurring gate failures and phases that need many rounds or run long
- issues fixed by hand in Chat
- user corrections
- adopted lessons not yet captured in a skill
- instructions that never influence outcomes (token cost)

Rank clusters by frequency × impact. Keep a cluster only when it has evidence from at least two runs, or from one verified severe failure.

Find target sections with `grep` instead of reading whole files. With more than three clusters, draft them in parallel, one subagent per cluster, each returning the fields in §3.

## 3. Propose

For each cluster, give:
- the evidence (run IDs, phases, quotes)
- the target file and section
- a minimal diff
- the expected benefit
- a regression check: an existing eval or a new eval case

Prefer tightening or deleting text over adding it. Keep `SKILL.md` lean and put details in references. Never weaken approvals, RBAC, safety or evidence gates, and never add secrets or tenant-specific values. Ask a fresh-context reviewer subagent to challenge each proposal against the evals, and drop those that fail. Re-verify only the claims the reviewer disputes, in one batch.

## 4. Apply after approval

- **In a clone of `github/awesome-copilot`:** edit `skills/foundry-agentic-loop/` and `extensions/foundry-agentic-loop-*` directly. Validate with `npm run skill:validate`, `npm run plugin:validate` and `node --test extensions/foundry-agentic-loop-*/tests/*.test.mjs`, then offer a pull request.
- **In a solution repository:** plugin files are replaced on update, so write project overrides instead. Copy the whole skill folder to `.github/skills/foundry-agentic-loop/` and edit it there; the workflow ignores a copy without `SKILL.md`, `references/sdd.md` and the four phase guides. Workflow subagents read project skills first, so overrides apply to the next run. Change workflow code only through an upstream pull request.
- **Afterwards:** reload with `extensions_reload` when extensions change, then measure with the bundled runner [`scripts/evals.mjs`](../scripts/evals.mjs) (Node 20+, Copilot CLI). It runs each case offline in a fresh workspace with the candidate skill as a project override, grades it with a second call and writes `.agentic-loop/evals/<timestamp>/results.json` and `summary.md`.
  1. Select cases without loading `evals/evals.json`: `node <skill>/scripts/evals.mjs index --target references/<file>.md` (also `--mode`, `--capability`). Add or update cases for new behavior, with `mode`, `capabilities`, `targets`, `risk` and, for stateful cases, a `fixture` under `evals/fixtures/`.
  2. Run `node <skill>/scripts/evals.mjs run --target references/<file>.md --base <base-commit>` (or `--ids 4,29`); in a solution repository, `--base` can be the installed plugin skill folder. Failing cases that are unchanged since the base also run against the base skill.
  3. Pass only with exit code 0: no regressions, and every new or changed case passes. Fix regressions and rerun only those, once. Report failures that also fail at the base as pre-existing instead of iterating.
  4. Exit code 2 means the runner is unavailable (Copilot CLI missing or signed out): stop, report "evals unavailable", and leave lessons unchanged.
- **Lessons:** mark matching `docs/LOOP.md` lessons `adopted` only after a passing regression run, and `validated` only after a later real run confirms the benefit. Write only the current workspace's `docs/LOOP.md`; for lessons from other solution folders, report the status change for their owners. Offer to upstream generalizable improvements.
observability.md 5.9 KB
# Observability contract

Reference for the `foundry-agentic-loop` skill: the end-to-end monitoring contract the generated infra must satisfy. `foundry-agentic-loop` declares the intent (telemetry **ON by default**, one Application Insights, keyless); this file holds the baseline infra, per-tier instrumentation, agent-observability, and content-capture detail. Defer SDK/instrumentation wiring to `appinsights-instrumentation` and role assignments to the `microsoft-foundry/rbac` sub-skill.

End-to-end monitoring is **on by default**: every tier - **backend, hosted agents, MCP servers, and Foundry models** - emits OpenTelemetry into **one Application Insights** resource so a single distributed trace follows a request from the browser through the backend, the agent loop, each tool/MCP call, and every model call. The generated Bicep must provision and wire it.

## Baseline infra (generated Bicep)

- Provision **one Application Insights** resource (backed by a Log Analytics workspace) shared by all components - this is what makes the **Application Map** and end-to-end transaction search work.
- Inject its connection string into every app, agent, and MCP server as `APPLICATIONINSIGHTS_CONNECTION_STRING`; authenticate the telemetry channel with each component's **managed identity** via the **Monitoring Metrics Publisher** assignments in [`rbac-contract.md`](rbac-contract.md) - **no instrumentation key, no connection-string secret on the data plane**.
- Build the exporter credential with `DefaultAzureCredential` and the component's managed identity client ID, never `ManagedIdentityCredential` alone: the same code exports as the managed identity in Azure and as the signed-in developer locally. The Bicep grants the deploying principal **Monitoring Metrics Publisher** too, so Verify proves telemetry without deploying.
- **Connect the same Application Insights resource to the Foundry project** (Foundry portal → Agents → Traces → Connect, or an Application Insights connection on the project) so Foundry **server-side** agent/model traces land in the same resource.
- Grant operators **Log Analytics Reader** on the resource so they can query telemetry.

## Per-tier instrumentation (defer wiring to `appinsights-instrumentation`)

| Tier | How it's instrumented | What lands in Application Insights |
| --- | --- | --- |
| **Backend** (API) | Azure Monitor OpenTelemetry distro (`configure_azure_monitor()` / `useAzureMonitor()` / `.UseAzureMonitor()`); auto-instruments inbound + outbound HTTP | Request/dependency spans, logs, metrics; W3C `traceparent` propagated to agents, MCP servers, and models |
| **Hosted agent** (Copilot SDK or MAF) | See *Agent observability* below | `invoke_agent` / `chat` / `execute_tool` spans, GenAI metrics, prompts & responses (when content capture is on) |
| **MCP server** | Azure Monitor OTel distro on the server process; record tool name, status or error class, duration and input/output sizes or item counts as span attributes, never arguments or results (see capture below) | Tool-call spans that nest under the agent's `execute_tool` span via propagated trace context |
| **Foundry models** | Foundry **server-side tracing** (automatic once App Insights is connected) plus model-SDK instrumentation when you call models from your own code | `gen_ai` chat spans: model, token usage, finish reason, and prompt/response content (when capture is on) |

## Agent observability

- **MAF** is natively instrumented (`ENABLE_INSTRUMENTATION=true`) and emits `invoke_agent` / `chat` / `execute_tool` spans and `gen_ai` metrics. When the hosting adapter already exports to Application Insights, don't start a second exporter; otherwise call `configure_azure_monitor(connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"])` once at startup.
- **Copilot SDK:** the hosting adapter exports host spans from `APPLICATIONINSIGHTS_CONNECTION_STRING`. The Copilot runtime is a separate producer: it exports its `invoke_agent` / `chat` / `execute_tool` spans over OTLP only when the client gets a `telemetry` config pointing `COPILOT_OTLP_ENDPOINT` at a reachable receiver, such as a collector with the Azure Monitor exporter. The reference agent [`copilot-sdk-with-toolbox.py`](copilot-sdk-with-toolbox.py) adds its own spans at the toolbox boundary. Follow [copilot-sdk-foundry.md](copilot-sdk-foundry.md#telemetry) for the route, identities and delivery checks.
- **Foundry-hosted agents** get `APPLICATIONINSIGHTS_CONNECTION_STRING` injected automatically and produce **server-side traces** (agent runs, tool calls, model calls, and the conversation view) with no code change; client-side instrumentation layers on top for your own app code.

## Capture the full detail (request data, prompts, responses)

Content capture is **off by default** because spans then carry prompts, completions, tool arguments/results, and request bodies (PII/secrets risk). Turn it on per layer:

| Layer | Flag to capture content |
| --- | --- |
| MAF | `ENABLE_SENSITIVE_DATA=true` (or `enable_sensitive_telemetry()`) |
| Copilot runtime | `telemetry={"capture_content": True}` |
| Model SDK (OpenAI / Azure AI Inference) | `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true` (or `AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED=true`) |
| Backend / MCP server | add request/response bodies and tool args/results as span attributes explicitly, behind a config flag that is off by default |

- **Treat captured content as sensitive:** keep capture off unless the user approves it, for dev/test with synthetic data. In production gate it behind config, redact secrets and PII before export, and apply production log access and retention.
- Set a distinct **cloud role name / `service.name`** per component (frontend, backend, agent, mcp-server) so the **Application Map** renders the topology and transactions correlate across tiers.
- Defer SDK/instrumentation wiring to `appinsights-instrumentation` and role assignments to the `microsoft-foundry/rbac` sub-skill.
rapid.md 8.9 KB
# Rapid prototyping

Build a working solution quickly in an **existing** Foundry project, driven from Chat. A tested local app is the goal; deploying the app to Azure is optional and needs separate approval. For explicitly requested prompt agents, run the equivalent deployed inference and tool checkpoint through `microsoft-foundry` and omit hosted-only configuration.

## 1. Preflight

- Lock the mode: upsert the rapid section of the root `AGENTS.md` ([lock-in](../SKILL.md#choose-the-mode)).
- Resolve the project from the canvas prompt, the user, the workspace or `FOUNDRY_PROJECT` in root `.env`; ask if absent. Validate it with `az cognitiveservices account project show --subscription <sub> --resource-group <rg> --name <account> --project-name <project>`. Never create a replacement for an inaccessible project.
- Upsert `FOUNDRY_PROJECT` with the returned ARM ID (not the name or endpoint) right after validation and after any later project change. Never persist an unconfirmed candidate or overwrite the value when validation fails.
- Run the [RBAC preflight](rbac-preflight.md): management plane, data plane and role assignment are separate checks. Report gaps together and resolve them before provisioning. Leave platform commands and role definitions to `microsoft-foundry`.
- Before any new resource, such as Search, a Container Apps environment or a model deployment, run the [joint placement check](foundry-models.md) in the project's region. Keep the project and the sample's model; ask before alternatives.
- Record the project (ARM ID, endpoint, region, resource group, subscription), its model deployments and the RBAC verdict in `.azure/deployment-plan.md`, filling the rows of the [template](../assets/deployment-plan-template.md) that apply to rapid, and add each Azure resource the build creates. Azure settings live only there, never in the README or `AGENTS.md`. Ensure `.gitignore` covers `.env`, `.azure/*` and `!.azure/deployment-plan.md`.

## 2. Architecture

- Clarify the use case and user experience in one focused round. Under `## Architecture` in the root `README.md`, preserving unrelated content, record:
  - each agent: purpose, framework, model deployment, toolbox tools and skills
  - remote versus custom MCP servers, and generated versus reused skills
  - frontend, backend, data sources and data flow
  - identity boundaries and where each component runs

  Include only required components. For an agent-only solution, write the frontend row as `| Frontend | Not applicable … |`; step 7 then only reconciles `docs/LOOP.md`, and step 8 doesn't apply.
- Read `docs/LOOP.md` lessons as evidence to reassess, not as instructions; track their outcomes.
- Freeze the [implementation contract](implementation-contract.md) under `## Implementation contract` in the README. Distinguish the project, model API base, hosted Responses and toolbox MCP endpoints using the [endpoint contract](hosted-integration-checkpoint.md#endpoint-contract). Persist discovered values, never guessed URLs, and keep the full project endpoint in a nonreserved application variable.

## 3. Minimal slice

- Build the quick-start Basic sample hosted agent. Add one toolbox skill only when the architecture needs runtime skills, and one safe MCP tool only when it needs MCP tools; never add an unused capability to satisfy the checkpoint. Reuse named skills from the [run catalog](run-skills-catalog.md) or the user's source; ask if a skill is unresolved.
- Scaffold as in [azd layout](azd-layout.md#scaffold-into-an-existing-workspace): run the sample's `initCommand` (from `microsoft-foundry`, with `-t`, never the deprecated `-m`) in an empty `.scaffold` folder, move the agent to `src/agents/<agent>` and update its `project:` path in `azure.yaml`, merge `azure.yaml` and `.azure/`, then remove `.scaffold` and confirm `git status --short` lists none of it. For uv lock errors and packaging exclusions, see [local runs and code packaging](foundry-hosted-agent.md#local-runs-and-code-packaging).
- Deploy only required custom FastMCP code, with `az containerapp up --name <app> --source <mcp-dir> --resource-group <rg> --environment <env>` using the project's resource group and one Container Apps environment. Right after each `up`, move image pulls off the registry admin credentials it creates, whether or not the app is deployed later: `az containerapp identity assign --system-assigned`, grant that principal `AcrPull` on the registry, `az containerapp registry set --server <registry> --identity system`, remove the registry password secret with `az containerapp secret remove`, then `az acr update --admin-enabled false` ([RBAC contract](rbac-contract.md)). Reuse remote servers. Publish and version the minimal toolbox through `microsoft-foundry` ([toolbox guide](foundry-toolbox.md)).
- Give each Python `pyproject.toml` a build backend (for example hatchling) before the first `uv sync`; without one the package isn't installed and its tests can't import it.
- For Copilot SDK agents, read [copilot-sdk-foundry.md](copilot-sdk-foundry.md) first. Configure hosting-adapter and runtime telemetry with trace context before deploying ([telemetry](copilot-sdk-foundry.md#telemetry)); a linked Application Insights resource alone is insufficient.
- Do not build the full orchestration, UI or backend yet.

## 4. Hosted checkpoint

Follow [hosted-integration-checkpoint.md](hosted-integration-checkpoint.md):
1. Code-deploy the minimal agent.
2. Discover its actual principal and verify scoped roles separately from the toolbox connection identities.
3. Using the deployed identity and caller context, prove a model request, plus a skill load and an MCP call when the architecture includes them (record excluded ones as `N/A` with the reason). Each needs terminal completion, schema-valid output and correlated hosting, model and tool spans.
4. Record the evidence under `## Hosted checkpoint` in the README, starting with `**Passed**` or `**Blocked**`, before expanding. The canvas tracks these README headings.

## 5. Expand

Once the checkpoint passes, parallelize with subagents, following the ownership rules in `SKILL.md`. Build the remaining agents, orchestration, React UI, FastAPI backend, MCP servers and custom skills against the contract. Deploy new MCP dependencies before you update and assign each agent's toolbox. Add [contract tests](hosted-integration-checkpoint.md#contract-tests), health checks and the proven telemetry setup to every component.

## 6. Deploy agents

Code-deploy the expanded agents with `microsoft-foundry`. Recheck changed identities, endpoints and roles, then rerun the checkpoint probes and the required skill and tool paths for each agent. Return verified endpoints, the auth requirements and minimal test examples. Use [bundled dependencies](copilot-sdk-foundry.md#dependency-packaging-fallback) only after remote dependency resolution fails, keeping Python 3.13 and code deployment.

## 7. Local acceptance

- Run FastAPI with reload and the Vite dev server, and confirm both respond. Reconcile them against the contract.
- Run E2E tests through UI → backend → deployed agents → MCP and tools, in parallel at the [Verify E2E concurrency](verify.md#3-test) c; report c and its inputs, and treat a 429 after retries as a failure. Verify a correlated trace reaches Application Insights without unapproved sensitive content. Fix failures before going further.
- Upsert `.env`: recheck `FOUNDRY_PROJECT`, then set the verified `LOCAL_FRONTEND`. Next, reconcile `docs/LOOP.md` from the [lessons template](../assets/loop-template.md); create it (and `docs/`) even when nothing failed, and say when no skill change is supported.
- Keep the servers running and report their URLs. **Then ask with `ask_user` whether to deploy the backend and frontend to Azure, and wait for the answer.** Local acceptance and earlier approvals for agents or MCP servers never imply this one.

## 8. Optional app deployment

Only after the user confirms:
1. Deploy the backend, then the frontend, with `az containerapp up --name <app> --source <dir> --resource-group <rg> --environment <env>`, reusing the project's resource group and Container Apps environment. Confirm each with `az containerapp show --name <app> --resource-group <rg> --query properties.provisioningState`.
2. Move image pulls off the registry admin credentials that `up` creates, as for MCP servers in [step 3](#3-minimal-slice), and disable the registry admin user again.
3. Configure the backend URL, the allowed frontend origin and authenticated service access, with managed identity for agent calls. Read an internal backend's FQDN (`<app>.internal.<environment-domain>`) from `az containerapp show`; never construct it.
4. Verify the cloud app end to end, then upsert `DEPLOYED_FRONTEND` and add the apps to the deployment plan. Return the URL and any sign-in requirements.

If the user declines, leave the working local app as it is.

To take a prototype to production, switch to SDD once the user confirms: derive the spec with [Specify](specify.md) `reverse`, rewrite the `AGENTS.md` section to SDD, then start the workflow.
rbac-contract.md 9.9 KB
# Keyless identity & RBAC contract

Reference for the `foundry-agentic-loop` skill: the principal → scope → role matrix the deployment creates: the generated **Bicep at provision**, plus an idempotent **`postdeploy` hook** for the hosted-agent runtime instance identity, which exists only after agent deploy. `foundry-agentic-loop` declares the intent (managed identities + least-privilege RBAC, no admin keys or connection strings on the control/data plane); this file holds the full matrix and notes. Defer exact role GUIDs and `Microsoft.Authorization/roleAssignments` syntax to the maintained `microsoft-foundry/rbac` sub-skill.

Two matrices live here, and they answer different questions:

| Matrix | Principal | When it applies |
| --- | --- | --- |
| [Runtime matrix](#runtime-matrix-service-managed-identities) (below) | The solution's **managed identities** | Created **by** the deployment: Bicep at provision, plus a `postdeploy` hook for the runtime instance rows |
| [Deployer prerequisites](#deployer-prerequisites-pre-flight) | The **caller** running the loop | Must already exist **before provisioning**, or provisioning breaks partway through |

## Runtime matrix (service managed identities)

Every component authenticates with a **managed identity** (user-assigned preferred) and **least-privilege RBAC** - no admin keys, no connection strings on the control/data plane.

| Principal (managed identity) | Scope / target resource | Azure role | Why |
| --- | --- | --- | --- |
| Frontend container app | Azure Container Registry (ACR) | **AcrPull** | Pull the frontend container image |
| Backend container app | Azure Container Registry (ACR) | **AcrPull** | Pull the backend container image |
| Backend container app | Foundry **AI account** (AI Services / Foundry account) | **Foundry User** | Invoke Foundry hosted agents |
| Foundry **project** managed identity | Azure Container Registry (ACR) | **Container Registry Repository Reader** (or **AcrPull**) | Pull the **hosted-agent image** at runtime |
| Foundry **project** managed identity | Foundry **AI account** | **Foundry User** | Project-brokered model inference (usually auto-assigned at project creation) |
| Hosted-agent **runtime instance** managed identity | Foundry **AI account** | **Cognitive Services OpenAI User** (+ **Foundry User** if it calls non-OpenAI account capabilities) | **BYOK direct inference** (Copilot SDK / MAF calling the model endpoint with its own token) |
| Hosted-agent **runtime instance** managed identity | Foundry **project** | **Foundry User** | Runtime skill download (the `AIProjectClient` skills API needs `agents/read`; without it the hosted invoke returns 500) |
| Hosted-agent **agent identity** (`agentIdentityId`) | Each downstream tool/grounding resource (Storage, AI Search / Foundry IQ backing service, Cosmos, Key Vault, ...) | The resource's data role (e.g. **Storage Blob Data Contributor**, **Search Index Data Reader**) | Default toolbox MCP path: Agent Service brokers tool and grounding access with the agent identity |
| Hosted-agent **runtime instance managed identity** | Azure AI Search (Foundry IQ backing service) | **Search Index Data Reader** | Escape hatch only: direct in-code Search / Foundry IQ retrieval with `DefaultAzureCredential`; not part of the default toolbox path |
| Foundry **project** managed identity | Log Analytics workspace | **Log Analytics Data Reader** | Only when **Foundry Evals** are in scope (read traces) |
| Frontend container app | Application Insights | **Monitoring Metrics Publisher** | Send telemetry |
| Backend container app | Application Insights | **Monitoring Metrics Publisher** | Send telemetry |
| Hosted-agent **runtime instance** managed identity | Application Insights | **Monitoring Metrics Publisher** | Send telemetry |
| MCP server (container app) | Application Insights | **Monitoring Metrics Publisher** | Send telemetry |
| Deploying principal (`principalId` from `AZURE_PRINCIPAL_ID`) | Application Insights | **Monitoring Metrics Publisher** | Local Verify runs send telemetry (the one non-service row) |

- Scope **Foundry User** to the **AI account** (not a single project) so the backend can invoke any hosted agent in it. Foundry User is the renamed Azure AI User; in Bicep, reference built-in roles by definition ID, never by display name.
- **Model inference depends on the inference path.** Project-brokered inference as the **agent identity** is covered by *implicit access* — no role needed. **BYOK direct inference** (the Copilot SDK / MAF agent calling the model endpoint with a token from `DefaultAzureCredential`) authenticates as the **runtime instance managed identity**, which has **no** implicit access — grant it **Cognitive Services OpenAI User** at the **AI account** scope or inference fails with `401 PermissionDenied`. The **blueprint** principal rejects role assignments (`PrincipalTypeNotSupported`); use its client ID only in MCP Easy Auth allow-lists. azd only auto-assigns `Foundry User` to the shared project agent identity, so create the runtime instance rows in the idempotent `postdeploy` hook ([grants after deploy](azd-layout.md#grants-after-deploy)).
- Scope **Cognitive Services OpenAI User** to the AI account hosting the model deployment.
- **Tool/MCP and default Foundry IQ grounding access are authorized against the `agentIdentityId`, not the runtime MI** — Agent Service brokers an agent-identity token for `AgenticIdentityToken`/`AgenticIdentity` connections. On **publish**, the agent can get a **new** `agentIdentityId`; repeat these assignments (shared-project roles don't carry over).
- **Runtime instance MI Search access is an escape hatch, not the baseline.** Grant **Search Index Data Reader** to the runtime instance MI only when the agent performs direct in-code Search / Foundry IQ retrieval instead of consuming the brokered toolbox grounding tool. The instance identity is minted at deploy/publish time, so make that grant reproducible in a `postdeploy` hook if the escape hatch is used. See [`foundry-iq-grounding.md`](foundry-iq-grounding.md#escape-hatch-direct-in-code-retrieval).
- Scope **AcrPull** to the registry and use managed-identity image pull - keep the ACR admin user disabled.
- Assign roles to each app/agent's identity, not to a shared principal, so the matrix stays least-privilege and auditable.

## Deployer prerequisites (pre-flight)

Every row of the runtime matrix above is created **by the deployment**, which means the caller running the loop needs rights both to create the resources *and* to write those role assignments. Missing caller rights do not fail cleanly at the start - they fail on the first operation that needs them, **after** partial resources exist.

These assignments must therefore be verified **before provisioning** by the [RBAC pre-flight](rbac-preflight.md), which diffs this table against the caller's effective assignments and reports every gap in one list.

| Principal | Scope | Azure role | Why |
| --- | --- | --- | --- |
| Caller (deploying principal) | Subscription | **Contributor** | Create the resource group and every resource in the reference architecture |
| Caller (deploying principal) | Subscription | **Role Based Access Control Administrator** | `Microsoft.Authorization/roleAssignments/write` - the Bicep and the `postdeploy` hook create the runtime matrix rows |
| Caller (deploying principal) | Existing resource group | **Contributor** | Create every resource of the solution in the existing group |
| Caller (deploying principal) | Existing resource group | **Role Based Access Control Administrator** | Write the runtime matrix rows in the group (ACR pulls, App Insights publishers, Foundry access) |
| Caller (deploying principal) | Existing Foundry **AI account** | **Foundry Account Owner** | Create projects, model deployments and account resources (control plane) |
| Caller (deploying principal) | Existing Foundry **project** | **Foundry Project Manager**, or **Foundry User** plus an account control-plane role | Create and publish hosted agents, skills, toolboxes (data plane) and project connections (control plane) |

- **Broader satisfies narrower.** **Owner** satisfies Contributor *and* Role Based Access Control Administrator; **User Access Administrator** satisfies Role Based Access Control Administrator; **Foundry Owner** satisfies both Foundry rows; Owner, Contributor and Cognitive Services Contributor satisfy the account row. A fully-permissioned caller therefore reports no gaps rather than a wall of false positives.
- **Control plane is not data plane.** Owner, Contributor and Foundry Account Owner carry no `dataActions`, so a subscription Owner still cannot create agents, skills or toolboxes until it also holds **Foundry User** on the project. Foundry User carries no write actions, so it needs an account control-plane role to create project connections.
- **Match role definition IDs.** The Azure AI roles were renamed to Foundry roles and the old display names no longer resolve; the pre-flight and the Bicep use built-in role definition IDs.
- **Inheritance counts.** An assignment at the subscription applies to the resource group and to the Foundry account and project beneath it; the pre-flight resolves effective (inherited and group-derived) assignments, not just direct ones.
- **An existing resource group replaces the subscription rows.** When the run deploys into a group that already exists, its rows apply instead; subscription grants still satisfy them through inheritance. SDD creates `rg-<env>`, so its first provision checks the subscription rows.
- **Foundry scopes only exist after the account/project do.** On a greenfield run the account and project are created by the deployment, so the pre-flight checks the inherited subscription-scoped rights that will allow their creation, and re-checks the concrete Foundry scopes when they are supplied (a brownfield run against an existing project).
- Grant these to the caller once, up front - do not work around a gap by falling back to admin keys or connection strings, which would break the keyless contract above.
rbac-preflight.md 10.2 KB
# RBAC pre-flight

Reference for the `foundry-agentic-loop` skill: the permission gate that runs **before any provisioning** in an agentic loop run, so missing role assignments are reported as one complete list *before* anything is created — never discovered one failure at a time, halfway through provisioning.

> **Why this exists.** An agentic loop run hit RBAC failures on the subscription, then the resource group, then the Foundry project. Each surfaced mid-provisioning, after partial resources already existed, and each had to be chased separately: request a grant, re-run, hit the next one. The whole set of missing assignments was knowable up front. This step makes it knowable up front.

This step is deliberately self-contained — it needs only the caller identity and the scopes in play — so rapid prototyping, SDD Specify and Deploy preflights reuse it unchanged.

## What it checks

The [runtime matrix](rbac-contract.md#runtime-matrix-service-managed-identities) describes the solution's **managed identities** — principals that do not exist yet before provisioning. The pre-flight checks the other half of the contract: the [**deployer prerequisites**](rbac-contract.md#deployer-prerequisites-pre-flight), the rights the **caller** needs both to create the resources and to write every role assignment the generated Bicep will create.

Concretely:

1. **Enumerate required** assignments from the deployer-prerequisites table.
2. **Resolve effective** assignments for the caller at each scope in play — subscription, resource group, Foundry AI account, and Foundry project — including **inherited** and **group-derived** ones.
3. **Diff** required against effective, applying role equivalence (see below).
4. **Report every gap at once** as `principal → scope → role`, with a remediation block a subscription owner can run as-is.
5. **Fail fast** on any gap. Nothing has been provisioned at this point, so there is no partial state to unwind.

### Scopes

| Scope | Resolved from | Notes |
| --- | --- | --- |
| Subscription | `AZURE_SUBSCRIPTION_ID` / `--subscription` | Checked when no existing resource group is in play: the run creates the group. |
| Resource group | `AZURE_RESOURCE_GROUP` / `--resource-group` | When the group **exists**, its rows replace the subscription rows; subscription grants still count through inheritance. A named group that does not exist yet falls back to the subscription rows. |
| Foundry AI account | `AZURE_AI_ACCOUNT_ID` / `--ai-account` | Pass when the run creates model deployments or other account resources in an existing account. |
| Foundry project | `AZURE_AI_PROJECT_ID` / `--ai-project` | Pass for every run against an existing project, such as rapid prototyping. |

Greenfield SDD runs create the resource group, account and project, so only the subscription rows apply. Brownfield runs check the concrete scopes as well, which is where per-resource grants diverge from subscription-level ones.

### Role equivalence

Roles are matched by **built-in role definition ID**, not display name. The Azure AI roles were renamed (Azure AI User → **Foundry User**, Azure AI Project Manager → **Foundry Project Manager**, Azure AI Account Owner → **Foundry Account Owner**, Azure AI Owner → **Foundry Owner**) and the old names no longer resolve in `az role assignment create`. Legacy names are still accepted in `--from-file` input. Custom roles are not evaluated: confirm them manually and record the exception.

A requirement is satisfied by an **equivalent-or-broader** assignment, so a fully-permissioned caller produces no findings rather than a wall of false positives:

| Requirement | Satisfied by |
| --- | --- |
| Deploy resources (subscription or existing resource group) | Contributor, Owner |
| Write role assignments (same scope) | Role Based Access Control Administrator, Owner, User Access Administrator |
| Foundry account control plane | Foundry Account Owner, Foundry Owner, Owner, Contributor, Cognitive Services Contributor |
| Foundry project: agents, skills, toolboxes, connections | Foundry Project Manager, Foundry Owner, or Foundry User (or Cognitive Services User) **plus** an account control-plane role |

Assignments **inherited** from a broader scope also satisfy a narrower one: subscription Contributor satisfies the resource-group Contributor requirement.

> **Control plane and data plane are separate.** Owner, Contributor, Foundry Account Owner and Cognitive Services Contributor grant `Microsoft.CognitiveServices/*` *actions* but no `dataActions`, so on their own they cannot create agents, skills or toolboxes. Foundry User grants the `dataActions` but no write actions, so on its own it cannot create project connections. A subscription Owner therefore still needs Foundry User on the project: the gap that surfaced *separately*, after the subscription and resource-group ones had already been fixed.

## Running it

```bash
# Reference check — copy references/check_rbac_preflight.py from the foundry-agentic-loop skill into ./scripts/
# SDD (greenfield): subscription only
python ./scripts/check_rbac_preflight.py --subscription "$AZURE_SUBSCRIPTION_ID"
# Rapid prototyping (existing project): add the group and project, and the account if the run creates deployments
python ./scripts/check_rbac_preflight.py --subscription "$AZURE_SUBSCRIPTION_ID" \
  --resource-group "$RESOURCE_GROUP" --ai-project "$FOUNDRY_PROJECT"
```

Live mode shells out to the **Azure CLI** — `az ad signed-in-user show` to resolve the caller, `az group exists` for a named resource group, then `az role assignment list --assignee <id> --scope <scope> --include-inherited --include-groups` per scope. No extra Python dependencies, and `az` is already present in any azd-driven run. Pass `--assignee` to check a principal other than the signed-in user (a service principal or CI identity).

`--from-file <observed.json>` replays a recorded set of assignments (or raw `az role assignment list` output) instead of calling Azure; raw output names no principal, so pass `--assignee` with it. Malformed input is an ERROR, never a PASS. Both the pass and the fail path can be exercised without a subscription.

## Verdicts

| Verdict | Exit code | Meaning |
| --- | --- | --- |
| `PASS` | `0` | Every required assignment is satisfied. **One** summary line is printed (`--quiet` prints nothing) — a fully-permissioned run adds no noise to the loop's output. |
| `BLOCKED` | `2` | One or more required assignments are missing. The full list is printed. **Do not start provisioning.** |
| `ERROR` | `1` | The check could not be evaluated (no caller identity, `az` unavailable, CLI failure). Resolve it rather than skipping the gate. |

`BLOCKED` is not a repair loop — unlike the [hosted integration checkpoint](hosted-integration-checkpoint.md#diagnostic-decision-tree), the loop cannot grant itself permissions. The correct response is to hand the report to someone who can, then re-run the pre-flight.

## Report contract

Print **every** missing assignment, not the first one — being handed the complete set in one go is the entire point:

```text
RBAC pre-flight: BLOCKED -- 2 required role assignments are missing.

  principal: sara@contoso.com (b3f1...c2a9)

  MISSING  sara@contoso.com -> /subscriptions/<sub-id>/resourceGroups/rg-app
           grant:   Role Based Access Control Administrator (f58310d9-a9f6-439a-9e8d-f62e7b41a168)
           accepts: Role Based Access Control Administrator | Owner | User Access Administrator
           why:     Microsoft.Authorization/roleAssignments/write - create the runtime matrix rows in the resource group
  MISSING  sara@contoso.com -> /subscriptions/<sub-id>/resourceGroups/rg-app/providers/Microsoft.CognitiveServices/accounts/aif-app/projects/proj
           grant:   Foundry User (53ca6127-db72-4b80-b1b0-d745d6d5456d)
           accepts: Foundry Project Manager | Foundry Owner | Foundry User (or Cognitive Services User) plus Foundry Account Owner, Owner, Contributor or Cognitive Services Contributor
           why:     Create and publish hosted agents, skills, toolboxes (data plane) and project connections (control plane)

Ask a subscription owner to run (role definition IDs are stable across renames):

  az role assignment create --assignee "b3f1...c2a9" --role "f58310d9-a9f6-439a-9e8d-f62e7b41a168" --scope "/subscriptions/<sub-id>/resourceGroups/rg-app"
  az role assignment create --assignee "b3f1...c2a9" --role "53ca6127-db72-4b80-b1b0-d745d6d5456d" --scope "/subscriptions/<sub-id>/resourceGroups/rg-app/providers/Microsoft.CognitiveServices/accounts/aif-app/projects/proj"

reference: skills/foundry-agentic-loop/references/rbac-contract.md#deployer-prerequisites-pre-flight
No resources have been created. Re-run this check once the assignments are in place.
```

Keep all four parts — the principal, one `MISSING` block per gap naming **scope, smallest grant and accepted alternatives**, the ready-to-run remediation, and the statement that nothing was created. The grant is the smallest role that completes the requirement given what the caller already holds (Foundry User for a caller who already has Contributor in the example). The remediation block is what turns the report into a single request to a subscription owner instead of a conversation.

## Where it sits in the loop

Run it **before provisioning**, after the target subscription/scopes are known and before any `azd provision`, resource creation, or Bicep deployment. Optionally wire the same script as a `preprovision` hook in `azure.yaml` so a direct `azd up` is gated too.

Record the verdict in `./.azure/deployment-plan.md`, in both modes, so a later failure can be told apart from a permission gap that was accepted and worked around.

## Reuse

The step depends only on the caller identity and the scopes in play, and touches no mode-specific state — so both agentic loop modes inherit it without extra wiring.

## Source

- [Azure built-in roles](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles)
- [Role Based Access Control Administrator](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles/privileged#role-based-access-control-administrator)
- [List role assignments with Azure CLI](https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-list-cli)
- [Microsoft Foundry role-based access control](https://learn.microsoft.com/en-us/azure/ai-foundry/concepts/rbac-azure-ai-foundry)
reference-architecture.md 3.4 KB
# Reference architecture service map

Reference for the `foundry-agentic-loop` skill: maps reference-architecture areas to the Azure services and companion skills to add **only when the spec needs them**. `foundry-agentic-loop` matches the spec against this map during skill suggestion; it is not a default resource list.

Use this map to propose additional Azure services only when they are needed or desired by the spec. Do not turn every reference-architecture box into a default resource. The greenfield baseline is a Foundry hosted agent on a Foundry model, with one toolbox carrying its skills, tools and grounding. The framework follows SKILL.md's rule: the Copilot SDK for agents that use runtime skills, Microsoft Agent Framework for basic agents and explicit workflows.

| Reference architecture area | Add when the spec needs | Suggested service / capability | Skill |
| --- | --- | --- | --- |
| Hosted Agent | Hosted runtime, agent deployment, prompt agent, agent tools, evals, model deployment, project setup | Azure AI Foundry hosted agents, Foundry projects, Foundry models, Foundry evals | `microsoft/azure-skills` / `microsoft-foundry` |
| Foundry Models | Frontier model deployment, region/SKU selection, quota/capacity planning | Foundry model deployments | `microsoft/azure-skills` / `microsoft-foundry` |
| Foundry IQ | Grounded knowledge, retrieval, vector/hybrid search, OCR/document extraction, speech features | Foundry IQ knowledge base exposed through the toolbox MCP endpoint; Azure AI Search / Document Intelligence / Speech as backing services when needed | `microsoft/azure-skills` / `azure-ai` - see [`foundry-iq-grounding.md`](foundry-iq-grounding.md) for the brokered toolbox path and direct-retrieval escape hatch |
| Work IQ / Microsoft 365 integration | Microsoft Graph, delegated auth, enterprise workflow integration, agent identity | Entra app registration or Entra Agent ID; use a Work IQ-specific skill if available outside `microsoft/azure-skills` | `microsoft/azure-skills` / `entra-app-registration`, `entra-agent-id` |
| Fabric IQ / analytics grounding | Analytics data, KQL exploration, data lake or blob-backed grounding | Azure Data Explorer for KQL analytics; Azure Storage/Data Lake for files and grounding data | `microsoft/azure-skills` / `azure-kusto`, `azure-storage` |
| Toolbox / APIs / MCP tools | API front door, MCP governance, tool routing, quotas, rate limits, semantic caching | Azure API Management as AI Gateway | `microsoft/azure-skills` / `azure-aigateway` |
| Control plane: Evals | Quality, safety, cost, and regression gates on traces | Foundry Evals and continuous evaluation | `microsoft/azure-skills` / `microsoft-foundry` |
| Control plane: Content Safety | Centralized LLM policies, jailbreak detection, content safety, token limits | AI Gateway policies and/or Foundry guardrails | `microsoft/azure-skills` / `azure-aigateway`, `microsoft-foundry` |
| Control plane: Observability | Telemetry, traces, metrics, app monitoring, KQL diagnostics | Application Insights, Azure Monitor, Log Analytics/KQL | `microsoft/azure-skills` / `appinsights-instrumentation`, `azure-kusto`, `azure-diagnostics` |
| Azure foundation | Deployment scaffold, validation, deployment execution, least-privilege access | azd/Bicep prep, validation, deploy, RBAC | `microsoft/azure-skills` / `azure-prepare`, `azure-validate`, `azure-deploy`, and the `microsoft-foundry/rbac` sub-skill |
run-skills-catalog.md 3.4 KB
# Run skills catalog

Reusable **run-phase** agent skills. Unlike the [build skills catalog](build-skills-catalog.md) (skills you install to help *build* the app), these are skills the **agent itself runs** at execution time.

**Reuse, don't regenerate.** When the prompt **explicitly names** one of these skills, reuse it as the local authoring artifact in `./skills/<skill-name>/`, then publish/update its governed version and attach it to the agent's toolbox using current `microsoft-foundry` guidance and supported commands. Verify the agent loads and uses that version. Also reuse explicitly supplied sources outside this catalog. If a named source cannot be resolved, ask rather than silently generating a replacement; author a new skill only when it is actually new or the user approves replacement.

This is a starter set of examples, not an exhaustive list.

| Repository               | Skill                            | Reuse when the prompt explicitly names |
| ------------------------ | -------------------------------- | -------------------------------------- |
| `github/awesome-copilot` | `eyeball`                        | Visually inspect a rendered UI or screenshot and report what is on screen or off-spec |
| `github/awesome-copilot` | `finalize-agent-prompt`          | Polish and finalize an agent's system / instruction prompt |
| `github/awesome-copilot` | `gtm-enterprise-account-planning`| Build an enterprise go-to-market account plan |
| `github/awesome-copilot` | `gtm-product-led-growth`         | Plan a product-led-growth (PLG) go-to-market motion |
| `github/awesome-copilot` | `incident-postmortem`            | Draft a structured incident postmortem (timeline, impact, root cause, action items) |
| `github/awesome-copilot` | `linkedin-post-formatter`        | Format content into a LinkedIn-ready post |
| `github/awesome-copilot` | `md-to-docx`                     | Convert Markdown into a DOCX document |
| `github/awesome-copilot` | `roundup`                        | Summarize multiple sources or items into a single roundup |
| `github/awesome-copilot` | `tldr-prompt`                    | Produce a concise TL;DR summary of long content |
| `aiappsgbb/agentic-loop`  | `factory-operations-triage`     | Triage smart-factory anomalies, maintenance signals, and quality deviations with evidence-backed operator actions |
| `aiappsgbb/agentic-loop`  | `production-flow-optimizer`     | Diagnose production bottlenecks and propose safe, constraint-aware flow and shift plans |
| `aiappsgbb/agentic-loop`  | `care-gap-outreach-planner`     | Prioritize care gaps and prepare consent-aware patient outreach without making clinical decisions |
| `aiappsgbb/agentic-loop`  | `post-discharge-care-coordinator` | Coordinate follow-up tasks, patient responses, and rule-based escalation after discharge |
| `aiappsgbb/agentic-loop`  | `loan-file-readiness-reviewer`  | Review lending files for completeness, consistency, freshness, and traceable exceptions |
| `aiappsgbb/agentic-loop`  | `mortgage-underwriting-coordinator` | Assemble evidence, conditions, and compliance checks for human mortgage underwriting |

For cataloged skills that declare a repository, name the source repository to the user, then install with the same command used for build skills:

```bash
gh skill install <repository> <skill> --agent github-copilot --scope project
```

After the skill is present locally, create and version it on Foundry and attach it to the toolbox.
sdd.md 11.1 KB
# Spec-driven development (SDD)

SDD turns a brief into a deployed, reproducible solution: a new Foundry project and Azure resources provisioned with azd and Bicep (AVM), keyless and monitored. The `foundry-agentic-loop-workflow` dynamic workflow runs four phases in sequence. Each phase runs in fresh-context subagents, follows its phase guide, must pass an evidence gate and leaves durable artifacts:

| Phase | Guide | Gate evidence | Artifacts |
| --- | --- | --- | --- |
| Specify | [specify.md](specify.md) | Independent review of EARS criteria, contract, workstreams, verification mapping, placement and RBAC verdict | `docs/spec.md`, `.azure/deployment-plan.md` |
| Implement | [implement.md](implement.md) | `azd provision`, hosted checkpoint, parallel workstreams integrated, builds and unit tests | `docs/implementation.md` |
| Verify | [verify.md](verify.md) | Local E2E and contract tests, independent spec-conformance review, agent evaluations | `docs/verify.md` |
| Deploy | [deploy.md](deploy.md) | `azd up`, health checks, deployed smoke and E2E tests | `docs/deploy.md` |

In each phase a lead does the work, a fresh-context reviewer reruns the checks, and fixers get up to `maxFixLoops` rounds. Only the reviewer's verdict passes a gate. Implement runs disjoint workstreams in parallel.

Phases reconcile existing artifacts instead of starting over, so reruns are safe. Lessons go to `docs/LOOP.md`. Each run writes a flight record to `.agentic-loop/runs/<runId>.json`, with status `running`, `awaiting-approval`, `blocked`, `deployed`, `verified` (or `specified`/`implemented` when `to` ends it early) or `error`, saved at the start, at the first step after a resume, at each gate and checkpoint, and at the end. A record that cannot be written pauses the run at `blocked-record-<step>`. One run is active per workspace: `.agentic-loop/active-run.json` holds its lease, and a second run refuses to start while that lease is under 30 minutes old.

## Start a run

1. **Check for a run.** List runs with `dynamic_workflows_manage` (`runs`) and match them to this workspace's `.agentic-loop/runs/` records. If one is running or paused, report it and offer to resume it instead of starting a second run.
2. **Preflight in Chat** (read-only): `az account show`, `azd auth login --check-status`, `azd ai agent --help` (azd Foundry extension), `microsoft-foundry` and the bootstrap. Report all gaps at once, and ask before installing or upgrading tools.
3. **Clarify once.** Ask, with choices, only the questions whose answers change the spec: users, data, tools, UX or compliance. Take the subscription, region and azd environment from the canvas prompt. Otherwise confirm the current az default subscription, leave the region to Specify's placement check, and derive a short environment name such as `claims-triage-dev`.
4. **Lock the mode.** Upsert the SDD section of the root `AGENTS.md` ([lock-in](../SKILL.md#choose-the-mode)). The workflow also writes it and refuses a workspace locked to rapid prototyping.
5. **Start** with `run_dynamic_workflow`, `name: "foundry-agentic-loop-workflow"`, and these `args`:

   | Arg | Purpose |
   | --- | --- |
   | `brief` | Required. Self-contained, with the user's answers and decisions |
   | `subscriptionId`, `location`, `environmentName` | Azure target when known |
   | `scenarioId` | Canvas prompt template |
   | `autonomy` | `gated` (default) pauses for spec approval; `auto` skips it |
   | `maxFixLoops` | Fix rounds per phase gate, 0–5 (default 2) |
   | `skipDeploy` | Stop after Verify |
   | `from` | Rerun from this phase; refused unless the latest record passed every earlier phase |
   | `to` | Last phase to run (default `Deploy`); `from` and `to` set to one phase run it alone |

   Pass `limits` only when the user sets them; defaults are 250 subagents, 4 concurrent and 12 hours of active time.
6. Report the run ID and the checkpoints ahead. The run continues in the background, posting phase and gate lines in Chat; the Foundry Agentic Loop canvas Build tab shows live agents. No input is needed until a checkpoint. Do not poll; the run notifies when it pauses or ends.

## Checkpoints and recovery

**Live status first.** For status, approve, resume or deploy requests, read the run with `dynamic_workflows_manage` (`runs`, then `inspect-run`) before its flight record. The run status is authoritative: a cancelled run keeps its last saved record status.

A pause posts a `Needs you:` line. Answer it in one message: what paused and why, the files to review, then the options as `ask_user` choices (approve or resume, change or fix first, leave paused).

| Pause | Meaning | Chat action on request |
| --- | --- | --- |
| `approve-spec-v1` | Spec ready for review | Summarize scope, assumptions, region and cost drivers; apply requested edits to the artifacts |
| `approve-spec-r<n>-v1` | The spec or plan changed since spec approval, before Implement round n | Summarize what changed; approving records the new fingerprint |
| `approve-deploy-v1` | Verified and ready to deploy (always pauses) | Summarize resources, cost, security and region impact; apply requested edits without deploying |
| `approve-deploy-r<n>-v1`, `approve-deploy-r<n>-a<k>-v1` | The deployment plan, spec, verify report or azd target changed since deploy approval, before round n or after its attempt k | Summarize what changed; approving records the new fingerprint |
| `blocked-record-<step>` | The flight record could not be written | Fix the path or permission shown, then resume |
| `blocked-<phase>-r<n>` | A gate failed after its fix rounds, a subagent ended twice without a report (usually a provider error), or a decision is needed (permissions, quota, cost, security) | List every issue from that phase and round in the flight record's `phases`, not just the first from the log. Fix and verify each root cause in the artifacts, record the evidence and `docs/LOOP.md` lessons. Resuming starts round n+1, which continues from the current state; its review first confirms these issues are resolved. To accept an issue instead, only on the user's explicit decision, write `[{"issue": "<exact issue>", "reason": "..."}]` to `.agentic-loop/waivers/<runId>.json` before resuming. After round 20, start a new run or rerun that phase alone with `from` and `to`. |

- Resume with `run_dynamic_workflow` and `resumeFromRunId` only when the user asks. When a canvas prompt says "Do not resume the run", don't: the canvas resumes it.
- **Liveness.** Workflow subagents don't appear in `list_agents` or `read_agent`, and one Implement step can run for over an hour without a record change. The canvas Build tab shows live subagent activity. Never cancel, pause or restart a run to unstick it; only the user decides that.
- **Provider errors.** A subagent that ends without a report is retried once with instructions to continue from the current state; a second miss blocks the phase, except for a workstream worker, which integration finishes. Check the session log, then resume.
- **Effort.** Subagents inherit the session's model and reasoning effort. Prefer medium or high: maximum effort multiplies step time.
- A run that ends in `error` with `workflow_limit_reached` resumes with only that limit raised, after approval. For other errors, read the run with `dynamic_workflows_manage` (`inspect-run`), fix the cause and start a new run.
- Never weaken a gate, skip a phase or report unverified checks as passed.
- For a single named phase, start the workflow with `from` and `to` both set to it; `from` alone also runs every later phase. Without the workflow, follow the phase guides yourself in order, checking each gate and pausing at the same approvals: ask before `azd provision`, `azd deploy` or `azd up`.

## SDD defaults

- **Placement:** a new resource group in the chosen subscription. Model `gpt-5.4-mini` unless the spec needs otherwise. Preferred region `eastus2` (`swedencentral` for EU data residency) unless the user chose one. The [joint placement check](foundry-models.md) decides before `AZURE_LOCATION` is persisted; record the preferred and deployed regions in the deployment plan.
- **Naming:** azd environment `<solution>-<stage>` in at most 20 characters; resource group `rg-<environment>`, set with `azd env set AZURE_RESOURCE_GROUP` right after scaffolding to replace the salted default. Check `az group exists` and add a short suffix on collision.
- **Skills first:** reusable agent behavior goes into Foundry skills authored at `skills/<name>/SKILL.md` and declared as `host: azure.ai.skill` services, so `azd deploy` versions them. Agents load them from the toolbox at runtime, so the image never copies `skills/`. Agents that use skills run on the Copilot SDK; basic agents and graph workflows use MAF.
- **Toolbox:** one `host: azure.ai.toolbox` service carries the skills, MCP tools (each through a `host: azure.ai.connection` service) and grounding. Agents list it in `uses` and map its `TOOLBOX_<NAME>_MCP_ENDPOINT` to `TOOLBOX_ENDPOINT` ([toolbox guide](foundry-toolbox.md)). Older azd extensions without upgrade approval fall back to ordered `postprovision` hooks.
- **Infra:** scaffold the Basic sample with `azd ai agent init .` in an empty `.scaffold` folder, then move it into place ([scaffold](azd-layout.md#scaffold-into-an-existing-workspace)); never `azd init -t <template>` followed by agent init (it rewrites the provider). `azure.yaml` then uses two `infra.layers`: `foundry` (`provider: microsoft.foundry`: account, project and the model deployments in `services.ai-project`) and `app` (Bicep with AVM, `dependsOn: [foundry]`) for user-assigned identities, Log Analytics and Application Insights connected to the project, one ACR pulled by managed identity, the Container Apps environment and apps, and every RBAC row. Agents use `host: azure.ai.agent`; MCP servers, backend and frontend use `host: containerapp` with `docker.remoteBuild: true`. Cosmos DB for NoSQL only when state is needed. No private networking unless required. Layout: [azd-layout.md](azd-layout.md).
- **Identity:** user-assigned managed identities. Bicep creates the [RBAC contract](rbac-contract.md) rows at provision; an idempotent `postdeploy` hook creates the runtime instance rows and the MCP Easy Auth allow-lists. The [RBAC preflight](rbac-preflight.md) runs in Specify; `BLOCKED` stops the run and hands the owner a ready-to-run grant block.
- **Repository:** `.gitignore` covers `.azure/*` with `!.azure/deployment-plan.md`, `.env` and build output. Python dependencies follow the [dependency contract](foundry-hosted-agent.md#python-dependency-contract-requirementstxt) and are locked with `uv.lock` or pinned requirements. `.gitattributes` sets `* text=auto eol=lf`.
- **Evaluations:** Verify always runs a small agent evaluation on spec scenarios (task adherence, intent resolution, and groundedness when grounded); content safety comes from Foundry guardrails. Add recurring or CI evaluations only on request.

## Teardown

Only on request and with explicit approval for the named environment and subscription: run `azd down --purge --force` from the workspace. It deletes the resource group and purges soft-deleted Foundry resources. Entra app registrations live outside the resource group: with the same approval, delete those recorded in `docs/implementation.md` with `az ad app delete --id <appId>`.
specify.md 4.4 KB
# Specify phase

Write the source of truth for an agentic solution. Apply the [skill defaults](../SKILL.md#defaults). This phase makes no Azure changes.

## Operating mode

- Read the brief, any canvas scenario, existing `docs/spec.md`, `.azure/deployment-plan.md`, `README.md` and the `docs/LOOP.md` lessons. Update existing artifacts instead of starting over.
- **Interactive:** ask once, with choices, only questions whose answers change scope: users, data, tools, UX or compliance.
- **In the workflow:** never ask. Take the documented default, or the safest reasonable one when none applies, record it under Assumptions and continue. Return `blocked` only for decisions on permissions, quota, cost or security.

## Sub-commands

| Command | Action |
| --- | --- |
| *(none)* | Create or update both artifacts |
| `sync` | Update the spec from the current code and `docs/*.md`; list any drift |
| `reverse` | Derive the spec from an existing or rapid-prototype workspace (root `README.md`, `azure.yaml`, `src/`) |
| `validate` | Run the checklist below and report only the gaps |
| `devcontainer` | Copy [devcontainer.json](../assets/devcontainer.json) to `.devcontainer/devcontainer.json`; it pins tested azd and uv versions, so bump them deliberately and record the change |

## Steps

1. **Preflight (read-only).** Run `az account show`, `azd auth login --check-status` and `azd ext list`, and record the subscription, tenant and signed-in principal. Run the [joint placement check](foundry-models.md) for the model and region, and the [RBAC preflight](rbac-preflight.md) for the caller. Run `az group exists -n rg-<env>` and add a short suffix on collision.
2. **Spec.** Write `docs/spec.md` from [spec-template.md](../assets/spec-template.md):
   - Write acceptance criteria in EARS form: "When <trigger>, the <system> shall <response>".
   - Freeze the [implementation contract](implementation-contract.md).
   - Split the build into at most four workstreams with exclusive files.
   - Map every requirement to a verification check.
   - Apply the [app-access default](../SKILL.md#defaults): no end-user sign-in only when all app data is sample, synthetic or public; for private or user-specific data, ask for the access model and default to internal ingress or Entra sign-in.
   - Keep it proportional: freeze interfaces, schemas, auth, errors and decisions, and leave internal algorithms, storage layouts and retry mechanics to Implement unless the brief requires them. Most specs fit in about 600 lines.
3. **Deployment plan.** Write `.azure/deployment-plan.md` from [deployment-plan-template.md](../assets/deployment-plan-template.md). It covers the target, placement evidence, RBAC verdict and grant block, resources, cost drivers and environment variables.
4. **Repository.** Ensure `.gitignore` covers `.azure/*`, `!.azure/deployment-plan.md`, `.env` and build output, and `.gitattributes` sets `* text=auto eol=lf`. Commit only when asked.
5. **Review.** In the workflow, a fresh reviewer checks the artifacts. Interactively, run `validate` yourself.

## Validate checklist

- No `[NEEDS CLARIFICATION]` markers remain. Each open item is an Assumption with a default and an owner.
- Every functional requirement has EARS criteria and a verification row. Non-functional requirements are measurable.
- The contract names every service, environment variable, endpoint, schema, protocol and auth method. Its versions row requires exact pins and image tags, resolved at Implement to the latest stable release, with the `github-copilot-sdk` API verified before any code is generated.
- Seed and decision rules (spec sections 9–10) make every scenario's outcome computable from frozen facts. Tables are well formed, and no credential or `Authorization` literal appears.
- There are at most four workstreams, and they own disjoint files.
- The spec is proportional: it freezes no internal algorithm, storage layout or retry mechanic that the brief does not require.
- The spec records the access model and why. With end-user sign-in, it names the SPA pre-authorization and how automated browser tests get a user token.
- Placement shows the model is available with quota in the region. The RBAC verdict is `READY`, or `BLOCKED` with a ready-to-run grant block.
- Companion skills appear only when a requirement needs them.

## Gate

Pass only when both files exist and the checklist holds. Report: status, summary, artifacts, assumptions, issues and lessons.
verify.md 5.3 KB
# Verify phase

Prove that the implementation meets `docs/spec.md` before anything is exposed publicly. Apply the [skill defaults](../SKILL.md#defaults), and use `microsoft-foundry` for agent operations. On a rerun, re-read `docs/verify.md` and rerun only the checks that are not passed, plus anything their fixes touch.

Until Deploy is approved, run the frontend and backend locally and never deploy them, even with internal ingress. Redeploy a hosted agent, or an MCP server it calls, only when its code changed. Infra fixes may re-provision once app images come from `${SERVICE_<NAME>_IMAGE_NAME=}` ([image parameters](azd-layout.md#container-app-settings)), but must not add public ingress.

Run every azd command from the workspace root, with `AZURE_DEV_USER_AGENT=microsoft_foundry_skill` set inline.

## 1. Preflight

- **azure.yaml:** every agent has `kind: hosted`, `protocols`, and a `codeConfiguration` whose `entryPoint` exists. Every Container Apps name is 32 characters or fewer.
- **Infra:** `az bicep build --file infra/app/main.bicep` succeeds.
- **Dependencies:** they are locked.
- **Local config:** wire `.env` and any local settings from `azd env get-values`. Show key names only, never values. Secrets resolve through managed identity, never as literals.

## 2. Run locally

1. Start each component in the background with telemetry on:
   - MCP servers
   - the backend
   - the frontend
   - `azd ai agent run --no-client` for each agent

   Poll readiness with a timeout. If a component fails to start, stop and report its exit code and the key log lines.
2. Run `azd ai agent invoke --local "<scenario>"` for each agent; it proves readiness and skill load only: toolbox calls using `AgenticIdentityToken` fail locally ("requires AgentInstanceClientId and AgentBlueprintClientId"). Check the backend health route, and check that the UI loads.
3. Upsert `LOCAL_FRONTEND` in `.env` once the UI works. Leave the app running for the user (detached when available) and document how to start it.

## 3. Test

| Check | Evidence |
| --- | --- |
| **Acceptance** | One automated test per EARS ID: contract tests for the frozen contract, and E2E through the frontend's `/api` proxy (Playwright when there is a UI). Run E2E cases in parallel at c = max(1, ⌊0.8 × TPM × minutes per case ÷ tokens per case⌋), measured from one case's Responses `usage` and duration (TPM = capacity × 1000), and record c and its inputs in `docs/verify.md`. A 429 after retries is a failure. |
| **Hosted** | `azd ai agent invoke <agent> "<scenario>"` against the deployed version. Run `azd deploy <agent>` first if the agent code changed. Retry 424 or 502 warm-up responses with backoff. |
| **Telemetry** | A trace from this run, including backend spans, reaches Application Insights (query `requests` or `dependencies` in the last 30 minutes). Local exporters sign in as the developer ([observability](observability.md)). |
| **Evaluation** | Write at least 10 rows from the spec scenarios to `tests/eval/dataset.jsonl`. Run `azd ai agent eval generate --agent <svc> --dataset tests/eval/dataset.jsonl --out-file tests/eval/<svc>.eval.yaml --evaluator builtin.task_adherence --evaluator builtin.intent_resolution`, adding `builtin.groundedness` when the agent is grounded. Then run `azd ai agent eval run --agent <svc> --config tests/eval/<svc>.eval.yaml`, one config per agent, check that its `Agent: <name> v<N>` line names that agent and the version just deployed, and keep the config with the results. |
| **Review** | A fresh-context reviewer checks the code and evidence against each requirement, the contract and the RBAC rows, and confirms from the container app revisions that no frontend or backend revision created after the Implement gate runs a new image (re-provisioning may add same-image revisions). |

## 4. Fix

1. Fix the root cause in the smallest scope.
2. Rerun the failing checks after each fix, and the full suite once after the last fix.
3. Upsert the lesson in `docs/LOOP.md` ([template](../assets/loop-template.md)).

Contract or scope changes go to `docs/spec.md` first. Never weaken a test or a threshold to get a pass.

For a failed evaluation row, read its per-row result. A judge can fail a correct refusal: when the row's stored tool calls and output match the contract, record it as an evaluator false negative with that evidence and keep the agent's behavior. Never change the agent just to raise a score.

## 5. Record

Write `docs/verify.md` with:

- the environment and the local URLs;
- a table mapping each requirement ID to its test, result and evidence;
- the evaluation scores with a link to the run;
- telemetry evidence;
- manual test steps;
- checks deferred to Deploy, with the reason;
- open issues.

## Gate

Pass only when:

- every component started in this run;
- every acceptance criterion has a passing test, a human-approved waiver listed in the workflow prompt (never self-granted) or, when only the deployed app can prove it (such as Easy Auth or public ingress), a check deferred to Deploy;
- the report lists evidence items (`{claim, source, result}`, up to 12); a pass without evidence counts as failed;
- each evaluator meets the spec's threshold (0.8 pass rate by default);
- a trace reached Application Insights;
- the review found no unresolved defects.

Report status, summary, artifacts, assumptions, issues and lessons.
scripts/
evals.mjs 22.0 KB
#!/usr/bin/env node
// Eval harness for the foundry-agentic-loop skill (Node >= 20, no dependencies). Usage: references/improve.md.
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { cp, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";

const SKILL_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const SKILL_NAME = "foundry-agentic-loop";
export const MODES = ["rapid", "sdd", "improve", "shared"];
export const RISKS = ["low", "medium", "high"];
const TAG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
// Evals never reach Azure or the network: no shell, URLs, MCP servers or workflow tools, and files only inside the workspace.
export const AGENT_TOOLS = ["view", "glob", "grep", "skill", "create", "edit"];
const LOCKDOWN = ["--deny-tool", "shell", "--deny-tool", "url", "--disable-builtin-mcps", "--disallow-temp-dir", "--no-ask-user", "-s"];
const PREAMBLE = "[Eval harness] This is an offline evaluation workspace. Shell, network, Azure, workflow and extension tools are unavailable by design. "
    + "Where a step needs one, state the exact tool call or command you would run and why, then continue. Never claim that it ran. "
    + `Load the ${SKILL_NAME} skill when the task is in its scope.\n\n`;
const AUTH = /not (?:logged|signed) in|no authentication|authentication (?:failed|required)|copilot login|unauthori[sz]ed|\b401\b/i;
const MAX_TEXT = 40_000;
const USAGE = `Usage:
  node evals.mjs index [--mode m] [--target file] [--capability c] [--ids 1,2]
  node evals.mjs validate
  node evals.mjs run (--ids 1,2 | --target file | --mode m | --capability c) [--base <git-ref|dir>] [--skill <dir>]
                 [--out <dir>] [--model m] [--grader-model m] [--runner <cmd>] [--concurrency n]
                 [--timeout <seconds>] [--max-ai-credits n] [--evals <evals.json>]
Exit codes: 0 all pass (with --base: no regressions and every new or changed case passes), 1 failures, 2 evals unavailable.`;

export function parseArgs(argv) {
    const [command, ...rest] = argv;
    const opts = {};
    for (let i = 0; i < rest.length; i += 1) {
        const match = /^--([a-z-]+)(?:=(.*))?$/s.exec(rest[i]);
        if (!match) throw new Error(`Unexpected argument: ${rest[i]}`);
        const value = match[2] ?? rest[++i];
        if (value === undefined) throw new Error(`--${match[1]} needs a value.`);
        opts[match[1].replace(/-([a-z])/g, (_, c) => c.toUpperCase())] = value;
    }
    return { command, opts };
}

export async function loadCases(file) {
    return JSON.parse(await readFile(file, "utf8")).evals;
}

const list = value => String(value ?? "").split(",").map(item => item.trim()).filter(Boolean);
const matchesTarget = (targets, value) => targets.some(target => target === value || target.endsWith(`/${value}`));

export function filterCases(cases, { ids, mode, target, capability } = {}) {
    const wanted = new Set(list(ids).map(Number));
    return cases.filter(c => (!wanted.size || wanted.has(c.id))
        && (!mode || c.mode === mode)
        && (!target || matchesTarget(c.targets ?? [], target))
        && (!capability || (c.capabilities ?? []).includes(capability)));
}

export function indexLines(cases) {
    const short = text => {
        const line = String(text).replace(/\s+/g, " ").trim();
        return line.length > 80 ? `${line.slice(0, 79)}…` : line;
    };
    return cases.map(c => [c.id, c.mode, c.risk, c.capabilities.join(","), c.targets.join(","), short(c.prompt)].join(" | "));
}

export function validateCases(cases, { evalsDir, skillDir }) {
    const errors = [];
    const ids = new Set();
    for (const c of cases) {
        const at = `case ${c?.id}`;
        if (!Number.isInteger(c?.id) || ids.has(c.id)) errors.push(`${at}: id must be a unique integer`);
        ids.add(c?.id);
        for (const key of ["prompt", "expected_output"]) if (typeof c?.[key] !== "string" || !c[key].trim()) errors.push(`${at}: ${key} is required`);
        if (!Array.isArray(c?.expectations) || !c.expectations.length || c.expectations.some(e => typeof e !== "string" || !e.trim())) errors.push(`${at}: expectations must be non-empty strings`);
        if (!Array.isArray(c?.files)) errors.push(`${at}: files must be an array`);
        if (!MODES.includes(c?.mode)) errors.push(`${at}: mode must be one of ${MODES.join(", ")}`);
        if (!RISKS.includes(c?.risk)) errors.push(`${at}: risk must be one of ${RISKS.join(", ")}`);
        if (!Array.isArray(c?.capabilities) || !c.capabilities.length || c.capabilities.some(tag => !TAG.test(tag))) errors.push(`${at}: capabilities must be kebab-case tags`);
        if (!Array.isArray(c?.targets) || !c.targets.length) errors.push(`${at}: targets must list skill files`);
        else for (const target of c.targets) if (!existsSync(path.join(skillDir, target))) errors.push(`${at}: target ${target} does not exist`);
        if (c?.fixture !== undefined) {
            const dir = path.join(evalsDir, "fixtures", String(c.fixture));
            if (!TAG.test(String(c.fixture)) || !existsSync(dir)) errors.push(`${at}: fixture ${c.fixture} does not exist`);
            else for (const file of c.files ?? []) if (!existsSync(path.join(dir, file))) errors.push(`${at}: file ${file} is not in fixture ${c.fixture}`);
        } else if (c?.files?.length) errors.push(`${at}: files need a fixture`);
    }
    return errors;
}

// Returns the first JSON object embedded in the text (code fences and prose around it are ignored), or null.
export function extractJson(text) {
    const s = String(text ?? "");
    for (let start = s.indexOf("{"); start !== -1; start = s.indexOf("{", start + 1)) {
        let depth = 0;
        let quoted = false;
        let escaped = false;
        for (let i = start; i < s.length; i += 1) {
            const ch = s[i];
            if (quoted) {
                if (escaped) escaped = false;
                else if (ch === "\\") escaped = true;
                else if (ch === "\"") quoted = false;
            } else if (ch === "\"") quoted = true;
            else if (ch === "{") depth += 1;
            else if (ch === "}" && --depth === 0) {
                try {
                    const value = JSON.parse(s.slice(start, i + 1));
                    if (value && typeof value === "object" && !Array.isArray(value)) return value;
                } catch { /* try the next opening brace */ }
                break;
            }
        }
    }
    return null;
}

export function grade(c, text) {
    const rows = extractJson(text)?.expectations;
    if (!Array.isArray(rows) || rows.length !== c.expectations.length || rows.some(row => typeof row?.passed !== "boolean")) {
        return { status: "error", error: "The grader returned no valid JSON verdict.", expectations: [] };
    }
    const expectations = c.expectations.map((expectation, i) => ({ text: expectation, passed: rows[i].passed, evidence: String(rows[i].evidence ?? "").slice(0, 500) }));
    return { status: expectations.every(row => row.passed) ? "passed" : "failed", expectations };
}

export const signature = c => JSON.stringify([c.prompt, c.expected_output, c.expectations, c.fixture ?? null]);

// New or changed cases must pass outright; a failing unchanged case is a regression only when it passed at the base.
export function classify(current, base, changed) {
    if (current.status === "error") return "error";
    if (current.status === "passed") return "passed";
    if (changed) return "new-failing";
    if (!base) return "failed";
    if (base.status === "error") return "error";
    return base.status === "passed" ? "regression" : "pre-existing";
}

export function exitCode(results) {
    if (results.some(r => r.unavailable)) return 2;
    return results.every(r => ["passed", "pre-existing"].includes(r.verdict)) ? 0 : 1;
}

function exec(command, args, { cwd, timeoutMs = 0 } = {}) {
    return new Promise(resolve => {
        const child = spawn(command[0], [...command.slice(1), ...args], { cwd, stdio: ["ignore", "pipe", "pipe"] });
        let stdout = "";
        let stderr = "";
        let timedOut = false;
        const timer = timeoutMs ? setTimeout(() => { timedOut = true; child.kill("SIGTERM"); }, timeoutMs) : null;
        child.stdout.on("data", chunk => { stdout += chunk; });
        child.stderr.on("data", chunk => { stderr += chunk; });
        child.on("error", error => { clearTimeout(timer); resolve({ code: null, stdout, stderr, error }); });
        child.on("close", code => { clearTimeout(timer); resolve({ code, stdout, stderr, timedOut }); });
    });
}

const unavailable = r => r.error?.code === "ENOENT" || (r.code !== 0 && AUTH.test(`${r.stderr}\n${r.stdout}`));
const failure = r => (r.timedOut ? "timed out" : r.error?.message ?? `exit ${r.code}: ${(r.stderr || r.stdout).trim().slice(-500)}`);

async function git(cwd, args) {
    const r = await exec(["git"], ["-c", "user.name=evals", "-c", "user.email=evals@example.invalid", "-c", "commit.gpgsign=false", "-c", "core.fsmonitor=false", "-c", "gc.auto=0", ...args], { cwd });
    if (r.code !== 0) throw new Error(`git ${args[0]} failed: ${failure(r)}`);
    return r.stdout;
}

// A fresh Git workspace with the case fixture and the candidate skill installed as a project override, minus its evals.
export async function prepareWorkspace(ws, c, { evalsDir, skillDir }) {
    await mkdir(ws, { recursive: true });
    if (c.fixture) await cp(path.join(evalsDir, "fixtures", c.fixture), ws, { recursive: true });
    // Fixtures store .gitignore as "gitignore" so the repository still tracks the files it lists, such as a placeholder .env.
    if (existsSync(path.join(ws, "gitignore"))) await rename(path.join(ws, "gitignore"), path.join(ws, ".gitignore"));
    await cp(skillDir, path.join(ws, ".github", "skills", SKILL_NAME), {
        recursive: true,
        filter: src => path.relative(skillDir, src).split(path.sep)[0] !== "evals",
    });
    await git(ws, ["init", "-q"]);
    await git(ws, ["add", "-A"]);
    await git(ws, ["commit", "-q", "--no-verify", "-m", "eval fixture"]);
}

async function changedFiles(ws) {
    const out = await git(ws, ["status", "--porcelain", "--untracked-files=all"]);
    return out.split("\n").filter(Boolean).map(line => ({ state: line.slice(0, 2).trim(), file: line.slice(3).replace(/^"|"$/g, "") }));
}

async function graderPrompt(c, response, ws, changes) {
    let budget = MAX_TEXT;
    const files = [];
    for (const { state, file } of changes) {
        let body = "(deleted)";
        if (state !== "D") {
            const text = await readFile(path.join(ws, file), "utf8").catch(() => "(unreadable)");
            body = text.slice(0, Math.max(0, Math.min(8000, budget)));
            budget -= body.length;
        }
        files.push(`--- ${file} [${state}]\n${body}`);
    }
    return [
        "You grade one evaluation case for the foundry-agentic-loop skill. Judge only the evidence below; do not use tools.",
        "The agent ran offline without shell, network, Azure or workflow tools. Credit an action it says it would take when it names the exact tool call or command; never credit a claim that something ran or passed without evidence.",
        "Be strict: an expectation passes only when the evidence satisfies every clause of it. Never infer unstated actions; if any part is missing, mark it false and name the missing part.",
        "Reply with JSON only: {\"expectations\":[{\"text\":\"<expectation>\",\"passed\":true|false,\"evidence\":\"<short quote or reason>\"}]}, one entry per expectation, in order.",
        `\n## Prompt\n${c.prompt}`,
        `\n## Expected output\n${c.expected_output}`,
        `\n## Expectations\n${c.expectations.map((e, i) => `${i + 1}. ${e}`).join("\n")}`,
        `\n## Agent response\n${response.slice(0, MAX_TEXT) || "(empty)"}`,
        `\n## Files the agent changed\n${files.join("\n") || "(none)"}`,
    ].join("\n");
}

async function runCase(c, ctx, dir) {
    const started = Date.now();
    const ws = path.join(dir, "workspace");
    const done = extra => ({ id: c.id, durationMs: Date.now() - started, expectations: [], ...extra });
    await rm(dir, { recursive: true, force: true });
    await prepareWorkspace(ws, c, ctx);
    const credits = ctx.maxAiCredits ? ["--max-ai-credits", ctx.maxAiCredits] : [];
    const agent = await exec(ctx.runner, ["-p", PREAMBLE + c.prompt, "--allow-all-tools", "--trust-folder", "--available-tools", ...AGENT_TOOLS, ...LOCKDOWN,
        ...(ctx.model ? ["--model", ctx.model] : []), ...credits, `--share=${path.join(dir, "transcript.md")}`], { cwd: ws, timeoutMs: ctx.timeoutMs });
    if (unavailable(agent)) return done({ status: "error", unavailable: true, error: failure(agent) });
    if (agent.code !== 0) return done({ status: "error", error: `agent ${failure(agent)}` });
    const response = agent.stdout.trim();
    const changes = await changedFiles(ws);
    await writeFile(path.join(dir, "response.md"), `${response}\n`);
    await writeFile(path.join(dir, "changes.txt"), changes.map(row => `${row.state} ${row.file}\n`).join(""));
    const graderModel = ctx.graderModel ?? ctx.model;
    const grader = await exec(ctx.runner, ["-p", await graderPrompt(c, response, ws, changes), "--no-custom-instructions", "--available-tools", "view", ...LOCKDOWN,
        ...(graderModel ? ["--model", graderModel] : []), ...credits], { cwd: ws, timeoutMs: ctx.timeoutMs });
    await writeFile(path.join(dir, "grader.txt"), grader.stdout);
    // Keep the fixture and what the agent wrote; drop the Git metadata and, unless the agent edited it, the installed skill.
    await rm(path.join(ws, ".git"), { recursive: true, force: true });
    if (!changes.some(row => row.file.startsWith(".github/"))) await rm(path.join(ws, ".github"), { recursive: true, force: true });
    if (unavailable(grader)) return done({ status: "error", unavailable: true, error: failure(grader) });
    if (grader.code !== 0) return done({ status: "error", error: `grader ${failure(grader)}` });
    return done({ ...grade(c, grader.stdout), changes: changes.map(row => row.file) });
}

async function pool(items, size, fn) {
    const results = [];
    let next = 0;
    await Promise.all(Array.from({ length: Math.min(size, items.length) }, async () => {
        while (next < items.length) {
            const i = next++;
            results[i] = await fn(items[i]);
        }
    }));
    return results;
}

async function runAll(cases, ctx, root) {
    let stopped = false;
    return pool(cases, ctx.concurrency, async c => {
        if (stopped) return { id: c.id, status: "error", unavailable: true, error: "skipped: evals unavailable", expectations: [], durationMs: 0 };
        const result = await runCase(c, ctx, path.join(root, String(c.id)))
            .catch(error => ({ id: c.id, status: "error", error: error.message, expectations: [], durationMs: 0 }));
        if (result.unavailable) stopped = true;
        return result;
    });
}

// Resolves the base skill: a folder holding a previous copy (such as the installed plugin skill), or the skill exported at a Git ref.
export async function exportBase(ref, skillDir, evalsFile, root) {
    if (existsSync(path.join(ref, "SKILL.md"))) {
        const file = path.join(ref, "evals", "evals.json");
        const cases = existsSync(file) ? await loadCases(file) : [];
        return { skillDir: path.resolve(ref), cases: new Map(cases.map(c => [c.id, c])) };
    }
    const top = (await git(skillDir, ["rev-parse", "--show-toplevel"])).trim();
    const posix = file => path.relative(top, file).split(path.sep).join("/");
    const prefix = posix(skillDir);
    const tar = path.join(root, "skill.tar");
    await mkdir(root, { recursive: true });
    await git(top, ["archive", "--format=tar", "-o", tar, ref, "--", prefix || "."]);
    const extracted = await exec(["tar"], ["-xf", tar, "-C", root]);
    await rm(tar, { force: true });
    if (extracted.code !== 0) throw new Error(`tar failed: ${failure(extracted)}`);
    const shown = await exec(["git"], ["show", `${ref}:${posix(evalsFile)}`], { cwd: top });
    const cases = shown.code === 0 ? JSON.parse(shown.stdout).evals : [];
    return { skillDir: path.join(root, prefix), cases: new Map(cases.map(c => [c.id, c])) };
}

function summary(report) {
    const t = report.totals;
    const lines = [
        "# Agentic Loop eval run",
        "",
        `- Skill: \`${report.skill}\`${report.base ? ` · base \`${report.base.ref}\`` : ""} · model ${report.model ?? "default"}`,
        `- ${t.passed} passed, ${t.failed} failed, ${t.error} errors${report.base ? `, ${t.regression} regressions, ${t.newFailing} new or changed failing, ${t.preExisting} pre-existing` : ""} · exit ${report.exitCode}`,
        "",
        "| Case | Status | Verdict | Expectations | Seconds |",
        "| --- | --- | --- | --- | --- |",
        ...report.cases.map(r => `| ${r.id} | ${r.status} | ${r.verdict} | ${r.expectations.filter(e => e.passed).length}/${r.expectations.length} | ${Math.round(r.durationMs / 1000)} |`),
    ];
    for (const r of report.cases.filter(row => row.status !== "passed")) {
        lines.push("", `## Case ${r.id}: ${r.verdict}`);
        if (r.error) lines.push(`- Error: ${r.error}`);
        for (const e of r.expectations.filter(row => !row.passed)) lines.push(`- ✗ ${e.text}`, `  - ${e.evidence}`);
        if (r.base) lines.push(`- Base: ${r.base.status}${r.base.error ? ` (${r.base.error})` : ""}`);
    }
    return `${lines.join("\n")}\n`;
}

async function run(opts, ctx, out) {
    if (!["ids", "mode", "target", "capability"].some(key => opts[key])) throw new Error("Select cases with --ids, --target, --mode or --capability.");
    const cases = filterCases(await loadCases(ctx.evalsFile), opts);
    if (!cases.length) throw new Error("No eval case matches the selection.");
    if (!existsSync(path.join(ctx.skillDir, "SKILL.md"))) throw new Error(`No SKILL.md in ${ctx.skillDir}.`);
    const probe = await exec(ctx.runner, ["--version"], { timeoutMs: 60_000 });
    if (probe.code !== 0) throw new Error(`${ctx.runner.join(" ")} is not available (${failure(probe)})`);
    const baseDir = opts.base && path.resolve(ctx.cwd, opts.base);
    const baseRef = baseDir && existsSync(path.join(baseDir, "SKILL.md")) ? baseDir : opts.base;
    const exported = opts.base ? await exportBase(baseRef, ctx.skillDir, ctx.evalsFile, path.join(ctx.outDir, "base", "src")) : null;
    const startedAt = new Date().toISOString();
    out(`Running ${cases.length} case(s) → ${ctx.outDir}`);
    const results = await runAll(cases, ctx, ctx.outDir);
    if (exported && !results.some(r => r.unavailable)) {
        results.forEach((r, i) => { r.changed = !exported.cases.has(r.id) || signature(exported.cases.get(r.id)) !== signature(cases[i]); });
        const rerun = cases.filter((c, i) => results[i].status === "failed" && !results[i].changed);
        if (rerun.length) out(`Comparing ${rerun.length} failing case(s) against ${opts.base}`);
        for (const b of await runAll(rerun, { ...ctx, skillDir: exported.skillDir }, path.join(ctx.outDir, "base"))) {
            const r = results.find(row => row.id === b.id);
            r.base = b;
            if (b.unavailable) r.unavailable = true;
        }
    }
    results.forEach(r => { r.verdict = classify(r, r.base, r.changed); });
    const count = verdict => results.filter(r => r.verdict === verdict).length;
    const report = {
        schema: 1,
        startedAt,
        completedAt: new Date().toISOString(),
        skill: ctx.skillDir,
        base: exported ? { ref: baseRef, skill: exported.skillDir } : null,
        model: ctx.model ?? null,
        exitCode: exitCode(results),
        totals: {
            passed: count("passed"),
            failed: results.filter(r => r.status === "failed").length,
            error: count("error"),
            regression: count("regression"),
            newFailing: count("new-failing"),
            preExisting: count("pre-existing"),
        },
        cases: results.map((r, i) => ({ mode: cases[i].mode, ...r })),
    };
    await mkdir(ctx.outDir, { recursive: true });
    await writeFile(path.join(ctx.outDir, "results.json"), `${JSON.stringify(report, null, 2)}\n`);
    await writeFile(path.join(ctx.outDir, "summary.md"), summary(report));
    out(summary(report));
    if (report.exitCode === 2) out(`Evals unavailable: ${results.find(r => r.unavailable).error}`);
    return report.exitCode;
}

export async function main(argv, { cwd = process.cwd(), out = line => console.log(line), err = line => console.error(line) } = {}) {
    try {
        const { command, opts } = parseArgs(argv);
        const evalsFile = path.resolve(cwd, opts.evals ?? path.join(SKILL_DIR, "evals", "evals.json"));
        const evalsDir = path.dirname(evalsFile);
        if (command === "index") {
            indexLines(filterCases(await loadCases(evalsFile), opts)).forEach(line => out(line));
            return 0;
        }
        if (command === "validate") {
            const errors = validateCases(await loadCases(evalsFile), { evalsDir, skillDir: path.dirname(evalsDir) });
            errors.forEach(line => err(line));
            if (!errors.length) out("Eval cases are valid.");
            return errors.length ? 1 : 0;
        }
        if (command !== "run") throw new Error(`Unknown command: ${command ?? "(none)"}\n${USAGE}`);
        return await run(opts, {
            cwd,
            evalsFile,
            evalsDir,
            skillDir: path.resolve(cwd, opts.skill ?? SKILL_DIR),
            outDir: path.resolve(cwd, opts.out ?? path.join(".agentic-loop", "evals", new Date().toISOString().replace(/[:.]/g, "-"))),
            runner: opts.runner && existsSync(path.resolve(cwd, opts.runner)) ? [path.resolve(cwd, opts.runner)] : (opts.runner ?? "copilot").split(/\s+/).filter(Boolean),
            model: opts.model,
            graderModel: opts.graderModel,
            maxAiCredits: opts.maxAiCredits,
            concurrency: Math.max(1, Number(opts.concurrency ?? 3) || 3),
            timeoutMs: Math.max(1, Number(opts.timeout ?? 1200) || 1200) * 1000,
        }, out);
    } catch (error) {
        err(`Evals unavailable: ${error.message}`);
        return 2;
    }
}

if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
    process.exitCode = await main(process.argv.slice(2));
}

License (MIT)

View full license text
MIT License

Copyright GitHub, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.