[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6J4BT1QR22EQR0GF6RC7M7A":3,"skill-same:01M6J4BT1QR22EQR0GF6RC7M7A":86},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":43,"commitSha":44,"skillDirectory":45,"forksCount":46,"repositoryHtmlUrl":47,"repositoryHomepageUrl":6,"ownerHtmlUrl":48,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":49,"install":50,"resources":63},"01M6J4BT1QR22EQR0GF6RC7M7A","mcs-build",null,"Use this skill to build an agent in Copilot Studio from a researched agentspec.json. Runs pre-build validation (auth, env, connections, tools, model), then creates the agent, configures instructions, knowledge, tools, model, topics, and publishes. Supports single-agent, multi-agent, and connected-agent architectures. Use after \u002Fmcs-research when agentspec.json is ready, or to resume a partially completed build.","dayour\u002FMCS-Agent-Builder","dayour","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F27440189?v=4","01M6J4B4HCG47B9AN14ADC3FV5","01M6J4B4P4QYVAZ0C7PZ84E1XD",0,"MIT","https:\u002F\u002Fgithub.com\u002Fdayour\u002FMCS-Agent-Builder\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fmcs-build\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"mcs build","build","instructions","studio","architectures","env","connections","resume","ready","use","research","multi-agent","model","json","knowledge","Tools","validation","copilot studio","copilot","auth","2026-11-10 10:12:30",false,"---\nname: mcs-build\ndescription: \"Use this skill to build an agent in Copilot Studio from a researched agentspec.json. Runs pre-build validation (auth, env, connections, tools, model), then creates the agent, configures instructions, knowledge, tools, model, topics, and publishes. Supports single-agent, multi-agent, and connected-agent architectures. Use after \u002Fmcs-research when agentspec.json is ready, or to resume a partially completed build.\"\n---\n\n# MCS Agent Builder — Unified Hybrid Build Stack\n\nBuild agents in Microsoft Copilot Studio using the optimized hybrid approach: PAC CLI for listing agents and solution ALM, LSP wrapper for instructions, model, topics, knowledge, and full component sync, Dataverse API for file uploads and PvaPublish, and user-guided manual steps for new OAuth connections.\n\nThis skill handles all build modes:\n- **Single Agent** — standalone build\n- **Multi-Agent** — builds specialists first, then orchestrator with child connections\n\n## Build Discipline — Verify-Then-Mark\n\nThese rules apply to every build step, because unverified changes silently accumulate into broken agents.\n\n1. **Atomic tasks**: Every build step is a separate task. \"Generate file\" and \"upload file\" and \"run eval\" are three tasks, not one.\n2. **Verify after every action**: After each change, snapshot or read-back to confirm it worked.\n3. **Do not mark a task complete until verified**: If you can't verify, say \"I did X but couldn't verify Y\".\n4. **File generation is not deployment**: Writing a local file is not the same as uploading it to MCS.\n5. **Environment check**: Before PAC CLI ops, verify the agent's environment matches PAC CLI's active profile.\n6. **Attempt every MVP item**: Attempt every item in the spec tagged `phase: \"mvp\"`. If an item fails, document: (a) what was tried, (b) the specific error, (c) what's needed to unblock it. A failed attempt with a clear error is valuable; a silently skipped item is a build gap.\n7. **End-of-build reconciliation**: After all changes, walk the spec's component list and snapshot-verify each item. Every MVP item shows MATCH, PARTIAL (with reason), FAILED (with error), or BLOCKED (with dependency). Zero items should show SKIPPED.\n\n## Input\n\n```\n\u002Fmcs-build {projectId} {agentId}                                 # Full build (includes full guard)\n\u002Fmcs-build {projectId} {agentId} --quick                         # Quick guard (staleness + auth + env + PAC only)\n\u002Fmcs-build {projectId} {agentId} --allow-stale --stale-reason \"\u003Creason>\"  # Override knowledge staleness guard\n```\n\nReads from:\n- `Build-Guides\u002F{projectId}\u002Fagents\u002F{agentId}\u002Fagentspec.json` — the single source of truth (architecture, tools, instructions, model, topics, everything)\n\nWrites to:\n- `Build-Guides\u002F{projectId}\u002Fagents\u002F{agentId}\u002Fagentspec.json` — updates `buildStatus` field\n- `Build-Guides\u002F{projectId}\u002Fagents\u002F{agentId}\u002Fbuild-report.md` — customer-shareable summary\n\n## Progress Markers\n\nEmit `##PROGRESS##` JSON markers at each step transition. Steps: `auth`, `context`, `create`, `instructions`, `knowledge`, `tools`, `model`, `topics`, `publish`, `validate`. Format: `##PROGRESS## {\"step\":\"...\",\"label\":\"...\",\"status\":\"running|completed|failed|skipped\",\"detail\":\"...\"}`. Emit `##BUILD_COMPLETE##` at the end. Emit `##AUTH_REQUIRED##` when user action needed (e.g., OAuth consent). Always emit regardless of headless or interactive mode.\n\n---\n\n## Smart Build Account & Environment Gate\n\nEvery build targets a specific tenant and environment. This gate reads persisted context, confirms with the user, and verifies Azure CLI + Dataverse + PAC CLI (optional) all work before proceeding.\n\n> Full protocol: see reference\u002Fauth-gate.md\n\n---\n\n## Step 0.9: Populate Build Context\n\nAfter auth is verified, capture all derived state into `agentspec.json.buildStatus` so every subsequent step reads from one place instead of re-deriving URLs, IDs, and GUIDs.\n\n1. **From session-config.json** (looked up by accountId + environment name):\n   - `dataverseUrl`, `gatewayUrl`, `environmentId`\n\n2. **From Dataverse** (if `mcsAgentId` exists — resume build):\n   - `botSchemaName` — `GET bots(\u003CmcsAgentId>)` full entity (query without `$select` because it can miss fields)\n   - `gptComponentId` — FetchXML query for botcomponent where `parentbotid`=`\u003CmcsAgentId>` AND `componenttype`=15. Use FetchXML with `parentbotid` (logical name) because OData filter with `_parentbotid_value` is unreliable.\n\n3. **Persist to agentspec.json.buildStatus** — write all fields atomically.\n\n4. **Log Build Context:**\n   ```\n   Build Context:\n     Agent: {name} ({mcsAgentId || \"new — will be created in Step 1\"})\n     Environment: {environment} ({environmentId})\n     Dataverse: {dataverseUrl}\n     Gateway: {gatewayUrl}\n     Workspace: {workspacePath || \"will be created in Step 1e\"}\n     Tenant: {azTenantId}\n   ```\n\nAll subsequent steps use buildStatus fields directly: Dataverse calls use `dataverseUrl` + `mcsAgentId`, Gateway calls use `gatewayUrl` + `environmentId`, LSP push\u002Fpull uses `workspacePath`, description PATCH uses `gptComponentId`, PAC CLI uses `botSchemaName`.\n\nAfter Step 1 (create agent): update `mcsAgentId`, `botSchemaName`, `gptComponentId` from the newly created agent.\n\n---\n\n## Phase 0: Pre-Build Validation (Guard)\n\nValidate all prerequisites before expensive operations begin. Catches auth failures, missing connections, unreachable knowledge sources, and model gaps that would otherwise waste build time. Runs automatically at the start of every build — no separate guard step needed.\n\nSupports two modes:\n- **Full** (default): all 8 checks (Check 0 + Checks 1–7)\n- **Quick** (`--quick` flag on `\u002Fmcs-build`): Check 0 + Checks 1–3 only (staleness + auth + env + PAC)\n\nEach check produces `pass`, `warn`, `fail`, or `skipped` (when a dependency check failed). Run all checks even if early ones fail — report everything at once.\n\n### Check 0: Knowledge Freshness (Staleness Guard)\n\nValidates that build-critical knowledge cache files are not dangerously stale. Builds refuse to proceed with stale knowledge unless explicitly overridden.\n\n```bash\nnode tools\u002Fsync-orchestrator.js run --source knowledge-cache --json\n```\n\nReads the `last_verified` dates in `knowledge\u002Fcache\u002F` via the `knowledge-cache` sync adapter. The 8 Tier 1 files are listed in `tools\u002Fsync-adapters\u002Fknowledge-cache.js` (`TIER1` set).\n\n| Result | Criteria |\n|--------|----------|\n| `pass` | All Tier 1 cache files less than 14 days old |\n| `warn` | One or more Tier 1 files 3–14 days old |\n| `fail` | One or more Tier 1 files over 14 days old (critical staleness) |\n\n**Override:** If the user passes `--allow-stale` to `\u002Fmcs-build`, a `fail` becomes `warn` and the build proceeds. Log the override to `agentspec.json.buildStatus.staleKnowledgeOverride` with timestamp + user-supplied reason.\n\nIf fail without override: stop build. Report:\n```\nKnowledge cache is critically stale (>14 days). Build refused.\nRun: \u002Fmcs-sync — TAKE the knowledge-cache and docs-manifest cards, follow the action plan to refresh the affected files.\nOr override: \u002Fmcs-build {projectId} {agentId} --allow-stale --stale-reason \"\u003Creason>\"\n```\n\n### Check 1: Azure CLI Auth\n\nValidates current Azure CLI session is authenticated to the correct tenant.\n\n```bash\naz account show --query \"{user:user.name, tenant:tenantId}\" -o json\naz account get-access-token --resource https:\u002F\u002F{org}.crm.dynamics.com --query accessToken -o tsv\n```\n\n| Result | Criteria |\n|--------|----------|\n| `pass` | Signed in, token acquired, tenant matches spec\u002Fsession-config |\n| `warn` | Signed in but tenant can't be confirmed, or token expires within 10 min |\n| `fail` | Not signed in, token acquisition fails, or tenant mismatch |\n\nIf fail: stop checks that depend on Dataverse. Report: \"Run `az login --tenant {tenantId}` to authenticate.\"\n\n### Check 2: Environment Reachability\n\nValidates target Dataverse environment responds.\n\n```bash\nnode -e \"const {get} = require('.\u002Ftools\u002Flib\u002Fhttp'); get('{dvUrl}\u002Fapi\u002Fdata\u002Fv9.2\u002FWhoAmI').then(r => console.log(JSON.stringify(r)))\"\n```\n\n| Result | Criteria |\n|--------|----------|\n| `pass` | WhoAmI succeeds, environment URL matches spec |\n| `warn` | Responds but with throttling (429) or slow (>5s) |\n| `fail` | Unreachable, 401\u002F403, DNS failure, or env doesn't exist |\n\n### Check 3: PAC CLI Profile\n\nValidates PAC CLI targets the same environment. `pac auth list` + `pac env who`.\n\n| Result | Criteria |\n|--------|----------|\n| `pass` | Active profile matches target environment |\n| `warn` | PAC available but no profile selected |\n| `fail` | PAC CLI not installed or unreachable |\n\nPAC CLI failure is always a `warn` for overall status (API fallback exists).\n\n### Check 4: Required Connections\n\nValidates all connections from `agentspec.json.integrations[]` exist in the target environment.\n\n1. Read `agentspec.json.integrations[]` — extract required connector names\n2. Run `add-tool.js discover-connections --dataverse-url \u003Curl>`\n3. Match each required integration against discovered connections\n\n| Result | Criteria |\n|--------|----------|\n| `pass` | All required connections found and in usable state |\n| `warn` | Connection exists but status unknown or needs re-auth |\n| `fail` | One or more required connections missing |\n\nIf fail: report which connections are missing with manual creation instructions.\n\n### Check 5: Knowledge Sources Accessibility\n\nValidates all knowledge sources from `agentspec.json.knowledge[]` are reachable.\n\n- **Public URLs:** HTTP HEAD request, check for 200\u002F301\u002F302\n- **SharePoint sites:** Graph API `GET \u002Fsites\u002F{hostname}:\u002F{path}`\n- **Dataverse files:** Check `annotation` table for file existence\n\n### Check 6: Tool \u002F MCP Server Availability\n\nValidates all tools from `agentspec.json.tools[]` are configured and responsive.\n\n1. Read `agentspec.json.tools[]` — extract tool names and types\n2. For MCP servers: check `add-tool.js list-connections` output\n3. For Work IQ servers: verify Work IQ MCP is configured\n\n### Check 7: Model Availability\n\nValidates requested AI model is available for the target environment.\n\n```bash\nnode tools\u002Fisland-client.js list-models --env {envUrl}\n```\n\nMatch `agentspec.json.model.name` against available models.\n\n### Guard Output\n\nWrite results to `agentspec.json.guardReport`:\n\n```json\n{\n  \"guardReport\": {\n    \"status\": \"pass|warn|fail\",\n    \"mode\": \"full|quick\",\n    \"checkedAt\": \"2026-03-31T12:00:00Z\",\n    \"checks\": [{ \"name\": \"...\", \"status\": \"...\", \"summary\": \"...\", \"evidence\": [], \"fix\": null }],\n    \"blockingIssues\": [],\n    \"warnings\": [],\n    \"nextAction\": \"...\"\n  }\n}\n```\n\n**Status precedence:** `fail` > `warn` > `pass`. Any hard fail = overall fail.\n\n- **All pass:** proceed to Step 1\n- **Warnings only:** log warnings, proceed\n- **Any fail:** stop build, report blocking issues with remediation steps\n\n### Guard Progress Markers\n\n```\n##PROGRESS## {\"step\":\"guard-staleness\",\"label\":\"Checking knowledge freshness\",\"status\":\"running\"}\n##PROGRESS## {\"step\":\"guard-auth\",\"label\":\"Checking Azure CLI auth\",\"status\":\"running\"}\n##PROGRESS## {\"step\":\"guard-env\",\"label\":\"Checking environment\",\"status\":\"running\"}\n##PROGRESS## {\"step\":\"guard-connections\",\"label\":\"Checking connections\",\"status\":\"running\"}\n##PROGRESS## {\"step\":\"guard-knowledge\",\"label\":\"Checking knowledge sources\",\"status\":\"running\"}\n##PROGRESS## {\"step\":\"guard-tools\",\"label\":\"Checking tools\u002FMCP\",\"status\":\"running\"}\n##PROGRESS## {\"step\":\"guard-model\",\"label\":\"Checking model availability\",\"status\":\"running\"}\n```\n\n### Brief Completeness (always runs, even in quick mode)\n\n5. **Spec completeness**: instructions non-empty and \u003C 8000 chars, agent name non-empty, agent description present (warn if missing), at least 1 MVP capability\n\nIf workspace is missing, clear `workspacePath` and re-clone in Step 1e. If agent was deleted, clear `mcsAgentId` and re-create in Step 1.\n\n---\n\n## MVP Phase Filtering\n\nOnly build items tagged `phase: \"mvp\"`. Skip items tagged `phase: \"future\"`.\n\nScan the spec and compute build scope across capabilities, integrations, knowledge, and topics. Output a scope summary:\n```\n## Build Scope (MVP filter)\n- Capabilities: {N} MVP, {M} deferred\n- Integrations: {N} MVP, {M} deferred\n- Knowledge: {N} MVP, {M} deferred\n- Topics: {N} MVP, {M} deferred\n```\n\nIf all items of a type are `future`, skip that entire build step and note it. Deferred items are listed in the build report (Section 9) so the customer knows what's coming next.\n\n---\n\n## Step 0.25: Solution Type Gate\n\nReads `agentspec.json.architecture.solutionType`. If \"agent\" or not set — proceed. If \"hybrid\" — proceed, log which capabilities are flow-only. If \"flow\" or \"not-recommended\" — hard stop with explanation and override instructions (`architecture.solutionTypeOverride = true`).\n\n---\n\n## Step 0.5: Decision Gate\n\nReads `agentspec.json.decisions[]`, filters to MVP-relevant decisions, categorizes as hard-block (`architecture`, `infrastructure`) or soft-warning (`integration`, `model`, `topic-implementation`). Hard blocks stop the build. Soft warnings proceed with recommended defaults pre-applied.\n\n---\n\n## Before Building — Enrichment Check + Knowledge Cache + Learnings\n\n### Enrichment-Aware Build\n\nIf the spec was created via the Agent Wizard and background enrichment ran (check `agentspec.json._enrichment`):\n- **Instructions**: Enrichment may have generated instructions via Claude Sonnet. Review them during Step 2 — if quality is sufficient, use as-is. If not, spawn PE to revise (not regenerate from scratch).\n- **Eval sets**: Enrichment may have generated eval test sets. Review during Step 4.5 — if coverage is sufficient, use as-is. QA validates and enhances rather than regenerating.\n- **Architecture scoring**: Enrichment ran deterministic scoring (build path, first-party agent matching, channel suggestions). These are pre-applied to the spec.\n- **Research flags**: Check `agentspec.json.recommendations[]` where `source === \"enrichment\"` — these are integrations the resolver couldn't match. May need live research or manual configuration.\n\n### Knowledge Cache + Learnings\n\n1. Read `knowledge\u002Fcache\u002Fapi-capabilities.md` — check `last_verified` date\n2. If stale (> 7 days), refresh via WebSearch + MS Learn\n3. Read `knowledge\u002Fpatterns\u002Fdataverse-patterns.md` for API call patterns\n4. Read `knowledge\u002Flearnings\u002Fbuild-methods.md` — check for creation precedents and known gotchas\n5. Update cache files if new findings\n\n## Route: Determine Build Mode\n\nRead `agentspec.json` -> `architecture.type`:\n\n| Value | Build Path |\n|-------|-----------|\n| `Single Agent` | Standalone Build (below) |\n| `Multi-Agent` | Multi-Agent Build (below) |\n| `Connected Agent` | Standalone Build + external connection notes |\n\n---\n\n## On-Demand Teammates During Build\n\nTwo teammates are available on-demand when issues arise (not spawned at build start — only when specific conditions trigger them). This keeps simple builds fast while making complex builds resilient.\n\n**Research Analyst** — spawned when tool configuration fails (connector not found, auth mode mismatch, unexpected parameters). RA searches official docs and community, reports correct name\u002Fauth\u002Falternatives. Lead applies the fix, updates spec + cache, dismisses RA.\n\n**Prompt Engineer** — spawned when instructions need adjustment after tools are configured (tool names differ, planned tool unavailable, action parameters changed, instructions exceed 8000 chars). PE uses GPT co-generation (`generate-instructions`) to produce and merge revised instructions. QA reviews, lead applies via LSP push, dismisses PE.\n\n## Step Failure Protocol (Build-Time Error Handling)\n\nWhen any build step fails (LSP push error, Dataverse 4xx\u002F5xx, connector mismatch, publish ConcurrencyVersionMismatch, eval Direct Line failure, flow build error), follow the 3-attempt protocol from `CLAUDE.md` → \"Error Handling\" — do NOT just retry with a \"different approach\":\n\n**Attempt 1 — research-driven retry:**\n1. **Query claude-mem first** — vector search the error message + step name + connector\u002Fmodel\u002Fcomponent name. Prior fixes for this exact pattern often exist. If found, prefer that fix over a fresh research cycle.\n2. Read `knowledge\u002Flearnings\u002F` topic file relevant to the failing step (`build-methods.md`, `connectors.md`, `topics-triggers.md`).\n3. WebSearch for error string + \"Copilot Studio\".\n4. MS Learn MCP for official troubleshooting.\n5. Read back the API state (Dataverse query, LSP pull, `pac copilot list`) to confirm what actually happened.\n6. Retry with the researched approach.\n\n**Attempt 2 — superpowers 4-phase debug (NOT a generic retry):**\nIf Attempt 1 fails, do NOT retry the same operation with another small change. Invoke the superpowers debugging skill explicitly:\n1. **Hypothesize** — enumerate candidate root causes from the layer set: `auth-token | payload-schema | API-contract | connector-config | model-availability | tenant-policy | timing | concurrency | LSP-Dataverse-divergence`. List 3-5 hypotheses with the evidence supporting each.\n2. **Reproduce** — produce a minimal repro outside the build pipeline. For Dataverse failures, run the same `curl` directly. For LSP push failures, do a dry-run pull-then-push on a clean copy. Confirm the failure is deterministic.\n3. **Isolate** — design ONE discriminating test per top hypothesis. Examples: \"if it's auth, fresh token retry succeeds\"; \"if it's schema, payload-only modification reproduces it\"; \"if it's concurrency, sequential push succeeds\". Run the tests. Narrow to one layer.\n4. **Fix** — apply the targeted fix. Verify via API read-back. Log the isolated cause + fix to `knowledge\u002Flearnings\u002Fbuild-methods.md` (or the relevant topic file) so claude-mem will surface it on Attempt 1 next time.\n\n**Attempt 3 — escalate to user:**\nIf superpowers-debug doesn't isolate the cause in one cycle, escalate. Include: the hypothesis tree, what was tested, what remains uncertain, and the proposed next step (user manual MCS UI check, fresh tenant test, etc.).\n\n**Failure budget rules:**\n- A single build can absorb the 3-attempt protocol on at most TWO distinct steps before escalating the build itself.\n- Same-step third failure → escalate immediately, do not loop.\n- Always emit `##PROGRESS##` markers with `status: \"failed\"` and a `detail` summarizing which attempt was reached.\n\n---\n\n## Standalone Build (Single Agent)\n\n### Dataverse API Shorthand\n\nAll Dataverse calls use buildStatus fields from Step 0.9:\n\n```bash\nTOKEN=$(az account get-access-token --resource \u003CbuildStatus.dataverseUrl> --query accessToken -o tsv)\nDV=\"\u003CbuildStatus.dataverseUrl>\"\nBOT=\"\u003CbuildStatus.mcsAgentId>\"\nGPT=\"\u003CbuildStatus.gptComponentId>\"\n```\n\n**Publish + verify pattern:**\n```bash\ncurl -s -X POST \"$DV\u002Fapi\u002Fdata\u002Fv9.2\u002Fbots($BOT)\u002FMicrosoft.Dynamics.CRM.PvaPublish\" \\\n  -H \"Authorization: Bearer $TOKEN\" -H \"Content-Type: application\u002Fjson\" -d '{}'\nsleep 5\n# Query WITHOUT $select (synchronizationstatus returns null with $select)\ncurl -s \"$DV\u002Fapi\u002Fdata\u002Fv9.2\u002Fbots($BOT)\" -H \"Authorization: Bearer $TOKEN\" | node -e \"\nlet d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>{\n  const data=JSON.parse(d);\n  const ss=JSON.parse(data.synchronizationstatus||'{}');\n  const status=(ss.lastFinishedPublishOperation||{}).status||'pending';\n  console.log('Publish status: '+status);\n})\"\n```\n\n**Description PATCH:** Now handled automatically by `mcs-lsp.js push` (patches lines 1-2 of GptComponent `data` field after LSP sync).\n\n### Step 0: Resume Detection & Environment Verification\n\nRead `agentspec.json.buildStatus.completedSteps`. If the array has entries, this is a resumed build — log which steps will be skipped. Mapping: `\"created\"` -> skip Step 1, `\"instructions\"` -> skip Step 2 instructions, `\"knowledge\"` -> skip Step 2 knowledge, `\"tools\"` -> skip Step 3 tools, `\"model\"` -> skip Step 3 model, `\"topics\"` -> skip Step 4. Step 5 (publish) re-runs on every build because it's cheap and ensures latest state.\n\n### Step 1: Find or Create Agent\n\nCheck for existing agent before creating, to prevent duplicates on build resume or session restart.\n\n**1a.** Check `agentspec.json.buildStatus.mcsAgentId` — if set, verify via `pac copilot list`. If found, skip creation. If not found (deleted), clear ID and proceed.\n\n**1b.** If no ID, search `pac copilot list` for matching `displayName`. If found, store ID and skip creation.\n\n**1c.** Create new agent via Dataverse POST + PvaProvision:\n1. POST `bots` with:\n   - `name`, `schemaname`, `language: 1033`, `runtimeprovider: 0`\n   - `authenticationmode: 1` (Integrated — \"Authenticate with Microsoft\")\n   - `authenticationtrigger: 1` (AsNeeded)\n   - `configuration` JSON including `GenerativeAIRecognizer` and `contentModeration: \"Medium\"`\n   - Example configuration: `{ settings: { GenerativeActionsEnabled: true }, aISettings: { model: { modelNameHint: \"GPT5Auto\" }, contentModeration: \"Medium\" }, recognizer: { kind: \"GenerativeAIRecognizer\" } }`\n2. POST `PvaProvision` bound action\n3. Wait for `statuscode` to transition to `Provisioned(1)` (~5-15s)\n4. PATCH bot `name` field (LSP push updates GptComponent `displayName` but not the bot entity `name`)\n\n**Fallback:** `pac copilot create` (requires template extraction first).\n\n**1d.** Persist `mcsAgentId` to `agentspec.json.buildStatus` immediately. Add `\"created\"` to `completedSteps`.\n\n**1f. Flow Designer auto-spawn:** After the agent shell exists, scan `agentspec.json.architecture.solutionType` (and `buildPath`). If it matches `flow`, `hybrid`, or `automation`, spawn `flow-designer` (`Agent({ subagent_type: \"flow-designer\", isolation: \"worktree\", ... })`) to design Power Automate flow specs in parallel with Step 2-4. FD writes `flow-spec.md` to `Build-Guides\u002F\u003Cproject>\u002Fagents\u002F\u003Cname>\u002Fflows\u002F`. Skipped silently when solutionType is pure agent.\n\n#### 1e. Clone Agent Workspace (LSP)\n\n```bash\nnode tools\u002Fmcs-lsp.js clone \\\n  --workspace \"Build-Guides\u002F{projectId}\u002Fagents\u002F{agentId}\u002Fworkspace\" \\\n  --agent-id \"\u003CmcsAgentId>\" --agent-name \"\u003CdisplayName>\" \\\n  --env-id \"\u003CenvironmentId>\" --dataverse-url \"\u003CdataverseUrl>\" --gateway-url \"\u003CgatewayUrl>\"\n```\n\nStore the **agent subfolder** (the one containing `.mcs\u002Fconn.json`) in `buildStatus.workspacePath` — not the parent directory. Push\u002Fpull commands need the subfolder path.\n\nSkip if `buildStatus.workspacePath` exists and the directory has `.mcs\u002Fconn.json`.\n\n#### Pre-push Validation (run before every LSP push)\n\nBefore running `mcs-lsp.js push`:\n1. Workspace exists: `\u003CworkspacePath>\u002F.mcs\u002Fconn.json` present\n2. `agent.mcs.yml` line 1: starts with `# Name:` and is not `# Name: default`\n3. `agent.mcs.yml` line 2: is not `# default` (has actual description)\n4. Conversation starters: every entry has both `title` and `text` (missing title causes silent publish failure)\n5. Instructions: \u003C 8000 chars\n6. Freshness: if last pull was > 30 min ago, pull first to avoid ConcurrencyVersionMismatch\n\n`mcs-lsp.js push` now automatically patches `botcomponent.description`, `botcomponent.name`, and comment headers via Dataverse API after LSP sync.\n\n### Steps 2-4: Parallel Dispatch (Instructions, Knowledge, Tools, Topics)\n\nAfter Step 1 completes (agent shell exists in MCS), Steps 2-4 run **in parallel** to compress the build. Dispatch all four work items in a single message with multiple Agent tool calls:\n\n| Work item | Owner | Isolation | Output written to |\n|-----------|-------|-----------|-------------------|\n| Instructions (Step 2b) | Prompt Engineer (sub-agent) | `worktree` | `agent.mcs.yml` `instructions:` field |\n| Knowledge (Step 2 knowledge) | Lead | — | `knowledge\u002F*.mcs.yml` + Dataverse uploads |\n| Tools \u002F MCP (Step 3) | Lead | — | `actions\u002F*.mcs.yml` |\n| Topics (Step 4) | Topic Engineer (sub-agent) | `worktree` | `topics\u002F*.mcs.yml` + Gateway create-topic |\n\nLead-driven items (knowledge, tools) don't need worktree isolation because the lead serializes its own writes. Sub-agent items (PE, TE) MUST run in worktrees because they both touch `agent.mcs.yml` and `agentspec.json` adjacent paths.\n\nAfter all four return, the lead reads each output, merges as needed, and proceeds to Step 5 (publish). Step 5 is gated on every parallel item completing.\n\n**Resume behavior:** Each sub-step has its own `completedSteps` checkpoint. If `\"instructions\"` is already in `completedSteps`, the PE dispatch is skipped — same for `\"knowledge\"`, `\"tools\"`, `\"topics\"`.\n\n### Step 2: Configure Agent Metadata, Instructions & Knowledge\n\n**Skip check:** If `\"instructions\"` and `\"knowledge\"` are both in `completedSteps`, skip this entire step.\n\n**2a. Description & Starters:** Edit `agent.mcs.yml` — set lines 1-2 (name, description metadata) and `conversationStarters` (each entry needs both `title` and `text`). Push via LSP.\n\n**2b. Instructions:** Edit `agent.mcs.yml` `instructions:` field. Run instruction-capability alignment check first (verify MVP capabilities are addressed, future capabilities are not). Push via LSP. Checkpoint: add `\"instructions\"` to `completedSteps`.\n\n**Knowledge:** Create `.mcs.yml` files in `knowledge\u002F` folder for SharePoint sites and URLs. Use Dataverse API for file uploads (PDF, DOCX). Phase filter: only MVP entries. Checkpoint: add `\"knowledge\"` to `completedSteps`.\n\n**Initial Publish:** `pac copilot publish --bot \u003Cbot-id>`\n\n**On-demand PE trigger:** After Step 3 configures tools, if tool names differ from spec, spawn PE to adjust instructions.\n\n### Before Step 3: Consult Connector & Integration Learnings\n\nRead `knowledge\u002Flearnings\u002Fconnectors.md` and `integrations.md` — look for connector name mismatches, auth gotchas, known workarounds.\n\n### Step 3: Configure Tools & Model\n\n**Skip check:** If `\"tools\"` and `\"model\"` are both in `completedSteps`, skip this step.\n\n**3a. Model Selection:** Default to `GPT5Auto` (GPT-5 Auto — dynamically routes between general and reasoning). Edit `agent.mcs.yml` -> `aISettings.model.modelNameHint: GPT5Auto`. Only change if spec specifies a different model or the environment doesn't support preview models. Check available models via `island-client.js get-models`. Checkpoint: add `\"model\"`.\n\n**3b. Settings (type: \"setting\" integrations):** Patch `bot.configuration` via Dataverse. Always set: `GenerativeActionsEnabled: true`, `recognizer: GenerativeAIRecognizer`. Per-spec: web browsing, model knowledge, content moderation.\n\n**3c. Tool\u002FConnector\u002FMCP Configuration:**\n\n**Work IQ first:** For any M365 data integration (email, calendar, teams, sharepoint, onedrive, user profile, files, search), add Work IQ from the agent overview page. This adds 2 MCP servers that cover everything:\n\n- **Work IQ Copilot** (`mcp_M365Copilot`) — cross-M365 search and actions for mail, calendar, teams, sharepoint, onedrive, files, everything\n- **Work IQ User** (`mcp_MeServer`) — people, org chart, manager, direct reports\n\nNo need to add individual Mail, Calendar, Teams, SharePoint servers separately. These 2 replace all individual M365 MCP servers and connectors. Requires M365 Copilot license. Status: Preview (Mar 2026).\n\n1. Auto-discover connection refs: `node tools\u002Fadd-tool.js discover-connections --dataverse-url \u003Curl>`\n2. Check if `shared_a365mcpservers` connection exists (covers Work IQ)\n3. Match discovered connections to spec integrations — prefer Work IQ matches from the resolver's `workiqRecommended` field\n4. For matched: write YAML action files to `workspace\u002Factions\u002F`, push via LSP\n5. For unmatched: guide user to add Work IQ from overview page in MCS UI, re-discover, then write YAML + push\n\n**Gaps (use connectors instead):** Planner, Excel, Approvals, PowerPoint have no Work IQ equivalent — use Power Platform connectors.\n\n**When NOT to use Work IQ:** Non-M365 integrations (Dynamics 365, Dataverse, Fabric, third-party) use their own MCP servers or connectors as before.\n\nCheckpoint: add `\"tools\"` to `completedSteps`. Verify via LSP pull that `actions\u002F` has all expected tools.\n\n### Before Step 4: Consult Topic & Trigger Learnings\n\nRead `knowledge\u002Flearnings\u002Ftopics-triggers.md` — look for YAML patterns, adaptive card gotchas, node type issues.\n\n### Step 4: Author Topics (LSP Push)\n\n**Skip check:** If `\"topics\"` is in `completedSteps`, skip this step.\n\nUse **Topic Engineer** for validated YAML (dual model co-generation for 3+ node topics). Phase filter: only MVP topics. Topic type filter: only `custom` or `system` (customized) — `generative` topics are handled by orchestration, no YAML needed.\n\nFor each MVP custom\u002Fsystem topic:\n1. TE generates topic definition (trigger phrases, actions, description)\n2. QA reviews definitions\n3. Create via Gateway API (required — LSP push does not produce renderable new topics):\n   ```bash\n   node tools\u002Fisland-client.js create-topic --env \u003CenvId> --bot \u003CbotId> --topic-file \u003Cpath>\n   ```\n4. For adaptive card topics: create with text placeholder via Gateway, pull workspace, edit YAML to add `SendMessage` + `AdaptiveCardTemplate`, push via LSP (LSP can update existing topics safely)\n5. For system topic customization: edit in workspace, push via LSP\n6. **Conversation Start welcome card (ALWAYS):** Replace the default plain-text ConversationStart with an adaptive card welcome. Use `welcome-card.yaml` template — fill `{{AGENT_NAME}}`, `{{WELCOME_MESSAGE}}`, and capability action buttons from agentspec.json capabilities. Write to `workspace\u002FAgent\u002Ftopics\u002FConversationStart.mcs.yml`, then push via LSP (system topic update, not new topic creation). This is not optional — every agent gets a welcome card.\n7. Available adaptive card styles for topics (see `knowledge\u002Fpatterns\u002Ftopic-patterns\u002F`): `welcome-card.yaml` (welcome), `adaptive-card.yaml` (data display + form), `table-list-card.yaml` (tables\u002Flists), `carousel-card.yaml` (multi-card), `status-card.yaml` (progress\u002Fstatus), `approval-card.yaml` (approve\u002Freject), `confirmation-card.yaml` (review before submit), `feedback-card.yaml` (thumbs up\u002Fdown). Choose the style that best fits each topic's purpose.\n\nDo not use `mcs-lsp.js push` to create new custom topics because the LSP skips internal MCS registration (NLU trigger indexing, compilation). Gateway API `BotComponentInsert` handles all registration automatically.\n\nCheckpoint: add `\"topics\"` to `completedSteps`.\n\n### Step 4.4: Power Automate Flow Build\n\nRuns only when `agentspec.json.flows[]` has at least one entry. The agent's logical name and Dataverse environment must already exist (Step 1 done), and topic YAML must already be pushed because flows are registered to the agent as `InvokeFlowTaskAction` in topics.\n\n**Order of operations** — handled by `tools\u002Fflow-build.js`:\n\n1. Validate `flows[]` (delegates to `app\u002Flib\u002Fflow-spec.js`). Fast-fail on schema errors.\n2. Topo-sort: `kind=ai-tool` first, then `kind=agent-flow` (which can reference ai-tools by `name`).\n3. For each flow in order:\n   - **Plan**: skip if `id` set and `status=='published'` (Phase 5 will add content-hash drift detection).\n   - **Create**: `flowManager.createAIFlow` for ai-tool (category=7) or `flowManager.createFlow` for agent-flow (category=5, modernflowtype=1). Auto-derives `environment.name` from the Dataverse org.\n   - **Resolve cross-refs**: `aiFlowRef` → ai-tool's `id` (which exists because topo sort built it first).\n   - **Publish**: `flowManager.publishFlow` calls `POST \u002FPublishComponent?ActivateFlowOnPublish=true` — single bound action publishes the component AND activates runtime.\n   - **Persist**: write `id`, `status`, `lastSyncedAt` back to `agentspec.json.flows[i]`.\n4. Failure isolation: a flow that fails marks `status='failed'` + `lastBuildError`, and execution continues with other independent flows.\n\n```bash\n# Plan-only (no API calls) — useful before the first build\nnode tools\u002Fflow-build.js plan --spec Build-Guides\u002F\u003Cproject>\u002Fagents\u002F\u003Cagent>\u002Fagentspec.json\n\n# Build all flows\nnode tools\u002Fflow-build.js run \\\n  --spec Build-Guides\u002F\u003Cproject>\u002Fagents\u002F\u003Cagent>\u002Fagentspec.json \\\n  --org \"$DV\"\n\n# Build a single flow (e.g. after a fix)\nnode tools\u002Fflow-build.js run --spec \u003Cagentspec> --org \"$DV\" --only \u003CflowName>\n```\n\n**Verify-then-mark**: after the run, query Dataverse for each `flows[i].id` and confirm `componentstate=0` (Published) and `statecode=1` (Activated). The CLI does this implicitly via the `publishFlow` round-trip; an explicit read-back is added in Phase 5.\n\n**Agent-side tool registration**: registering an agent-flow as a callable tool (`actions\u002F\u003Cname>.mcs.yml` with `kind: TaskDialog, action: { kind: InvokeFlowTaskAction, flowId }`) is still authored as part of Step 4 (topics) — the flow build produces the `flowId` that those YAML files reference. Re-push the topic via `mcs-lsp.js` after the flow build if the YAML referenced `\u003CflowId-pending>` or similar placeholder.\n\nCheckpoint: add `\"flows\"` to `completedSteps` once every `flows[i]` is either `status='published'` or `status='failed'` (with the failure recorded — silent skip is forbidden).\n\n### Step 4.5: Post-Build Eval\n\n**Check:** If agent uses MCP servers with user-delegated auth, skip automated eval (Direct Line can't authenticate). Generate test cases for manual testing instead.\n\n**Auto mode (Direct Line):** Acquire token, run boundaries set (target 100%), run quality set (target 85%), write results to `agentspec.json.evalSets[].tests[].lastResult`.\n\n**Manual mode (Gateway API):** Upload eval sets via `island-client.js upload-evals`, run via `run-eval`, present summary. User checks results in MCS or runs `\u002Fmcs-eval` later.\n\nNo iterative boundaries\u002Fquality\u002Fedge-cases loop during build. Build is single-pass. User runs `\u002Fmcs-fix` for post-deployment issues.\n\n### Step 5: Publish (Dataverse PvaPublish)\n\nRe-runs on every build (even resume) because publishing is cheap and ensures latest state.\n\n```bash\ncurl -s -X POST \"$DV\u002Fapi\u002Fdata\u002Fv9.2\u002Fbots($BOT)\u002FMicrosoft.Dynamics.CRM.PvaPublish\" \\\n  -H \"Authorization: Bearer $TOKEN\" -H \"Content-Type: application\u002Fjson\" -d '{}'\n```\n\nVerify via `synchronizationstatus` (not just HTTP 200): query bot without `$select`, parse `lastFinishedPublishOperation.status`. Poll up to 6 attempts at 5s intervals. Also check `publishedon` is today.\n\nCommon failures: `MissingRequiredProperty: Title` (starter without `title`), `ConcurrencyVersionMismatch` (stale workspace), `InvalidComponent` (malformed YAML).\n\nCheckpoint: add `\"published\"` to `completedSteps` after `synchronizationstatus` shows `\"Succeeded\"`.\n\n### Step 5.5: QA Build Validation Gate\n\nAfter publish, spawn QA Challenger for formal validation. The lead collects reconciliation snapshots, runs automated drift detection (`drift-detect.py`), and QA analyzes everything: spec-vs-actual comparison, cross-reference validation, and deviation impact assessment. QA writes `qa-validation.md` with a verdict of PASS \u002F PASS WITH CAVEATS \u002F FAIL.\n\n> Full QA protocol: see reference\u002Fqa-validation-gate.md\n\n### Step 5.6: GPT Build Review\n\nAfter QA validation, fire GPT-5.5 via `multi-model-review.js`: `review-brief`, `review-instructions`, and per-topic `review-topics`. GPT findings merge with QA verdict (union of findings, stricter wins). If GPT finds a critical issue QA missed, escalate to user before writing buildStatus. If GPT is unavailable, proceed with QA verdict alone.\n\n### Step 6: Finalize agentspec.json buildStatus\n\nWrite the complete buildStatus. Most fields were written incrementally during checkpoints — this step ensures the final state is clean:\n\n```json\n{\n  \"buildStatus\": {\n    \"status\": \"published\",\n    \"lastBuild\": \"2026-02-18T...\",\n    \"mcsAgentId\": \"\u003Cbot-id>\",\n    \"environment\": \"\u003Cenv-name>\",\n    \"account\": \"\u003Caccount-label>\",\n    \"accountId\": \"\u003Csession-config-account-id>\",\n    \"publishedAt\": \"2026-02-18T...\",\n    \"completedSteps\": [\"created\", \"instructions\", \"knowledge\", \"tools\", \"model\", \"topics\", \"critical-gate\", \"capability-iteration\", \"edge-cases\", \"published\"],\n    \"lastCompletedStep\": \"published\",\n    \"lastError\": null\n  }\n}\n```\n\n---\n\n## Multi-Agent Build\n\nBuild specialists first, then orchestrator. Each specialist follows the standalone build flow with specialist-focused instructions and sharing enabled. The orchestrator connects to all specialists via Island Gateway API.\n\n> Full multi-agent protocol: see reference\u002Fmulti-agent-build.md\n\n---\n\n## End-of-Build Reconciliation\n\nAfter all changes, walk the spec's MVP-scoped component list and snapshot each item: agent name, model, instructions, knowledge sources, tools, triggers, publish status, (multi-agent) specialist connections and sharing. Collect deferred items list. Then spawn QA Challenger (Step 5.5) with the snapshot data, agentspec.json, and deferred items list.\n\n## Output: Build Summary Report\n\nAfter reconciliation, generate two outputs:\n\n### Terminal Output\n\n```\n## Build Complete: [Agent Name]\n\n**Status:** Published | **Environment:** [env] | **Account:** [account]\n**QA Validation:** PASS ({N}\u002F{N} items match, {M} cross-ref issues — see qa-validation.md)\n**Eval Sets:** boundaries {X}% | quality {X}% | edge-cases {X}%\n**Capabilities:** {N} passing, {M} failing, {K} not tested\n**Deferred:** {J} future items (see build report Section 9)\n\nReport saved: Build-Guides\u002F{projectId}\u002Fagents\u002F{agentId}\u002Fbuild-report.md\n\n**Next:** Review the build report, share with customer for approval. Run \u002Fmcs-eval for standalone re-runs.\n```\n\n### Build Report File\n\nWrite a customer-shareable build report to `build-report.md` with 11 sections: overview, architecture, capabilities, tools, knowledge, topics\u002Ftriggers, key behaviors, open questions, spec-vs-actual changes, eval status, and next steps.\n\n> Full template: see reference\u002Fbuild-report-template.md\n\n---\n\n## Post-Build Learnings\n\nTier 1 (auto): bump confirmed counts for routine builds. Tier 2 (user-confirmed): deviations, workarounds, discoveries. See `reference\u002Flearnings-capture.md` and `.claude\u002Frules\u002Flearnings-system.md`.\n","# MCS Agent Builder — Unified Hybrid Build Stack\n\nBuild agents in Microsoft Copilot Studio using the optimized hybrid approach: PAC CLI for listing agents and solution ALM, LSP wrapper for instructions, model, topics, knowledge, and full component sync, Dataverse API for file uploads and PvaPublish, and user-guided manual steps for new OAuth connections.\n\nThis skill handles all build modes:\n- **Single Agent** — standalone build\n- **Multi-Agent** — builds specialists first, then orchestrator with child connections\n\n## Build Discipline — Verify-Then-Mark\n\nThese rules apply to every build step, because unverified changes silently accumulate into broken agents.\n\n1. **Atomic tasks**: Every build step is a separate task. \"Generate file\" and \"upload file\" and \"run eval\" are three tasks, not one.\n2. **Verify after every action**: After each change, snapshot or read-back to confirm it worked.\n3. **Do not mark a task complete until verified**: If you can't verify, say \"I did X but couldn't verify Y\".\n4. **File generation is not deployment**: Writing a local file is not the same as uploading it to MCS.\n5. **Environment check**: Before PAC CLI ops, verify the agent's environment matches PAC CLI's active profile.\n6. **Attempt every MVP item**: Attempt every item in the spec tagged `phase: \"mvp\"`. If an item fails, document: (a) what was tried, (b) the specific error, (c) what's needed to unblock it. A failed attempt with a clear error is valuable; a silently skipped item is a build gap.\n7. **End-of-build reconciliation**: After all changes, walk the spec's component list and snapshot-verify each item. Every MVP item shows MATCH, PARTIAL (with reason), FAILED (with error), or BLOCKED (with dependency). Zero items should show SKIPPED.\n\n## Input\n\n```\n\u002Fmcs-build {projectId} {agentId}                                 # Full build (includes full guard)\n\u002Fmcs-build {projectId} {agentId} --quick                         # Quick guard (staleness + auth + env + PAC only)\n\u002Fmcs-build {projectId} {agentId} --allow-stale --stale-reason \"\u003Creason>\"  # Override knowledge staleness guard\n```\n\nReads from:\n- `Build-Guides\u002F{projectId}\u002Fagents\u002F{agentId}\u002Fagentspec.json` — the single source of truth (architecture, tools, instructions, model, topics, everything)\n\nWrites to:\n- `Build-Guides\u002F{projectId}\u002Fagents\u002F{agentId}\u002Fagentspec.json` — updates `buildStatus` field\n- `Build-Guides\u002F{projectId}\u002Fagents\u002F{agentId}\u002Fbuild-report.md` — customer-shareable summary\n\n## Progress Markers\n\nEmit `##PROGRESS##` JSON markers at each step transition. Steps: `auth`, `context`, `create`, `instructions`, `knowledge`, `tools`, `model`, `topics`, `publish`, `validate`. Format: `##PROGRESS## {\"step\":\"...\",\"label\":\"...\",\"status\":\"running|completed|failed|skipped\",\"detail\":\"...\"}`. Emit `##BUILD_COMPLETE##` at the end. Emit `##AUTH_REQUIRED##` when user action needed (e.g., OAuth consent). Always emit regardless of headless or interactive mode.\n\n---\n\n## Smart Build Account & Environment Gate\n\nEvery build targets a specific tenant and environment. This gate reads persisted context, confirms with the user, and verifies Azure CLI + Dataverse + PAC CLI (optional) all work before proceeding.\n\n> Full protocol: see reference\u002Fauth-gate.md\n\n---\n\n## Step 0.9: Populate Build Context\n\nAfter auth is verified, capture all derived state into `agentspec.json.buildStatus` so every subsequent step reads from one place instead of re-deriving URLs, IDs, and GUIDs.\n\n1. **From session-config.json** (looked up by accountId + environment name):\n   - `dataverseUrl`, `gatewayUrl`, `environmentId`\n\n2. **From Dataverse** (if `mcsAgentId` exists — resume build):\n   - `botSchemaName` — `GET bots(\u003CmcsAgentId>)` full entity (query without `$select` because it can miss fields)\n   - `gptComponentId` — FetchXML query for botcomponent where `parentbotid`=`\u003CmcsAgentId>` AND `componenttype`=15. Use FetchXML with `parentbotid` (logical name) because OData filter with `_parentbotid_value` is unreliable.\n\n3. **Persist to agentspec.json.buildStatus** — write all fields atomically.\n\n4. **Log Build Context:**\n   ```\n   Build Context:\n     Agent: {name} ({mcsAgentId || \"new — will be created in Step 1\"})\n     Environment: {environment} ({environmentId})\n     Dataverse: {dataverseUrl}\n     Gateway: {gatewayUrl}\n     Workspace: {workspacePath || \"will be created in Step 1e\"}\n     Tenant: {azTenantId}\n   ```\n\nAll subsequent steps use buildStatus fields directly: Dataverse calls use `dataverseUrl` + `mcsAgentId`, Gateway calls use `gatewayUrl` + `environmentId`, LSP push\u002Fpull uses `workspacePath`, description PATCH uses `gptComponentId`, PAC CLI uses `botSchemaName`.\n\nAfter Step 1 (create agent): update `mcsAgentId`, `botSchemaName`, `gptComponentId` from the newly created agent.\n\n---\n\n## Phase 0: Pre-Build Validation (Guard)\n\nValidate all prerequisites before expensive operations begin. Catches auth failures, missing connections, unreachable knowledge sources, and model gaps that would otherwise waste build time. Runs automatically at the start of every build — no separate guard step needed.\n\nSupports two modes:\n- **Full** (default): all 8 checks (Check 0 + Checks 1–7)\n- **Quick** (`--quick` flag on `\u002Fmcs-build`): Check 0 + Checks 1–3 only (staleness + auth + env + PAC)\n\nEach check produces `pass`, `warn`, `fail`, or `skipped` (when a dependency check failed). Run all checks even if early ones fail — report everything at once.\n\n### Check 0: Knowledge Freshness (Staleness Guard)\n\nValidates that build-critical knowledge cache files are not dangerously stale. Builds refuse to proceed with stale knowledge unless explicitly overridden.\n\n```bash\nnode tools\u002Fsync-orchestrator.js run --source knowledge-cache --json\n```\n\nReads the `last_verified` dates in `knowledge\u002Fcache\u002F` via the `knowledge-cache` sync adapter. The 8 Tier 1 files are listed in `tools\u002Fsync-adapters\u002Fknowledge-cache.js` (`TIER1` set).\n\n| Result | Criteria |\n|--------|----------|\n| `pass` | All Tier 1 cache files less than 14 days old |\n| `warn` | One or more Tier 1 files 3–14 days old |\n| `fail` | One or more Tier 1 files over 14 days old (critical staleness) |\n\n**Override:** If the user passes `--allow-stale` to `\u002Fmcs-build`, a `fail` becomes `warn` and the build proceeds. Log the override to `agentspec.json.buildStatus.staleKnowledgeOverride` with timestamp + user-supplied reason.\n\nIf fail without override: stop build. Report:\n```\nKnowledge cache is critically stale (>14 days). Build refused.\nRun: \u002Fmcs-sync — TAKE the knowledge-cache and docs-manifest cards, follow the action plan to refresh the affected files.\nOr override: \u002Fmcs-build {projectId} {agentId} --allow-stale --stale-reason \"\u003Creason>\"\n```\n\n### Check 1: Azure CLI Auth\n\nValidates current Azure CLI session is authenticated to the correct tenant.\n\n```bash\naz account show --query \"{user:user.name, tenant:tenantId}\" -o json\naz account get-access-token --resource https:\u002F\u002F{org}.crm.dynamics.com --query accessToken -o tsv\n```\n\n| Result | Criteria |\n|--------|----------|\n| `pass` | Signed in, token acquired, tenant matches spec\u002Fsession-config |\n| `warn` | Signed in but tenant can't be confirmed, or token expires within 10 min |\n| `fail` | Not signed in, token acquisition fails, or tenant mismatch |\n\nIf fail: stop checks that depend on Dataverse. Report: \"Run `az login --tenant {tenantId}` to authenticate.\"\n\n### Check 2: Environment Reachability\n\nValidates target Dataverse environment responds.\n\n```bash\nnode -e \"const {get} = require('.\u002Ftools\u002Flib\u002Fhttp'); get('{dvUrl}\u002Fapi\u002Fdata\u002Fv9.2\u002FWhoAmI').then(r => console.log(JSON.stringify(r)))\"\n```\n\n| Result | Criteria |\n|--------|----------|\n| `pass` | WhoAmI succeeds, environment URL matches spec |\n| `warn` | Responds but with throttling (429) or slow (>5s) |\n| `fail` | Unreachable, 401\u002F403, DNS failure, or env doesn't exist |\n\n### Check 3: PAC CLI Profile\n\nValidates PAC CLI targets the same environment. `pac auth list` + `pac env who`.\n\n| Result | Criteria |\n|--------|----------|\n| `pass` | Active profile matches target environment |\n| `warn` | PAC available but no profile selected |\n| `fail` | PAC CLI not installed or unreachable |\n\nPAC CLI failure is always a `warn` for overall status (API fallback exists).\n\n### Check 4: Required Connections\n\nValidates all connections from `agentspec.json.integrations[]` exist in the target environment.\n\n1. Read `agentspec.json.integrations[]` — extract required connector names\n2. Run `add-tool.js discover-connections --dataverse-url \u003Curl>`\n3. Match each required integration against discovered connections\n\n| Result | Criteria |\n|--------|----------|\n| `pass` | All required connections found and in usable state |\n| `warn` | Connection exists but status unknown or needs re-auth |\n| `fail` | One or more required connections missing |\n\nIf fail: report which connections are missing with manual creation instructions.\n\n### Check 5: Knowledge Sources Accessibility\n\nValidates all knowledge sources from `agentspec.json.knowledge[]` are reachable.\n\n- **Public URLs:** HTTP HEAD request, check for 200\u002F301\u002F302\n- **SharePoint sites:** Graph API `GET \u002Fsites\u002F{hostname}:\u002F{path}`\n- **Dataverse files:** Check `annotation` table for file existence\n\n### Check 6: Tool \u002F MCP Server Availability\n\nValidates all tools from `agentspec.json.tools[]` are configured and responsive.\n\n1. Read `agentspec.json.tools[]` — extract tool names and types\n2. For MCP servers: check `add-tool.js list-connections` output\n3. For Work IQ servers: verify Work IQ MCP is configured\n\n### Check 7: Model Availability\n\nValidates requested AI model is available for the target environment.\n\n```bash\nnode tools\u002Fisland-client.js list-models --env {envUrl}\n```\n\nMatch `agentspec.json.model.name` against available models.\n\n### Guard Output\n\nWrite results to `agentspec.json.guardReport`:\n\n```json\n{\n  \"guardReport\": {\n    \"status\": \"pass|warn|fail\",\n    \"mode\": \"full|quick\",\n    \"checkedAt\": \"2026-03-31T12:00:00Z\",\n    \"checks\": [{ \"name\": \"...\", \"status\": \"...\", \"summary\": \"...\", \"evidence\": [], \"fix\": null }],\n    \"blockingIssues\": [],\n    \"warnings\": [],\n    \"nextAction\": \"...\"\n  }\n}\n```\n\n**Status precedence:** `fail` > `warn` > `pass`. Any hard fail = overall fail.\n\n- **All pass:** proceed to Step 1\n- **Warnings only:** log warnings, proceed\n- **Any fail:** stop build, report blocking issues with remediation steps\n\n### Guard Progress Markers\n\n```\n##PROGRESS## {\"step\":\"guard-staleness\",\"label\":\"Checking knowledge freshness\",\"status\":\"running\"}\n##PROGRESS## {\"step\":\"guard-auth\",\"label\":\"Checking Azure CLI auth\",\"status\":\"running\"}\n##PROGRESS## {\"step\":\"guard-env\",\"label\":\"Checking environment\",\"status\":\"running\"}\n##PROGRESS## {\"step\":\"guard-connections\",\"label\":\"Checking connections\",\"status\":\"running\"}\n##PROGRESS## {\"step\":\"guard-knowledge\",\"label\":\"Checking knowledge sources\",\"status\":\"running\"}\n##PROGRESS## {\"step\":\"guard-tools\",\"label\":\"Checking tools\u002FMCP\",\"status\":\"running\"}\n##PROGRESS## {\"step\":\"guard-model\",\"label\":\"Checking model availability\",\"status\":\"running\"}\n```\n\n### Brief Completeness (always runs, even in quick mode)\n\n5. **Spec completeness**: instructions non-empty and \u003C 8000 chars, agent name non-empty, agent description present (warn if missing), at least 1 MVP capability\n\nIf workspace is missing, clear `workspacePath` and re-clone in Step 1e. If agent was deleted, clear `mcsAgentId` and re-create in Step 1.\n\n---\n\n## MVP Phase Filtering\n\nOnly build items tagged `phase: \"mvp\"`. Skip items tagged `phase: \"future\"`.\n\nScan the spec and compute build scope across capabilities, integrations, knowledge, and topics. Output a scope summary:\n```\n## Build Scope (MVP filter)\n- Capabilities: {N} MVP, {M} deferred\n- Integrations: {N} MVP, {M} deferred\n- Knowledge: {N} MVP, {M} deferred\n- Topics: {N} MVP, {M} deferred\n```\n\nIf all items of a type are `future`, skip that entire build step and note it. Deferred items are listed in the build report (Section 9) so the customer knows what's coming next.\n\n---\n\n## Step 0.25: Solution Type Gate\n\nReads `agentspec.json.architecture.solutionType`. If \"agent\" or not set — proceed. If \"hybrid\" — proceed, log which capabilities are flow-only. If \"flow\" or \"not-recommended\" — hard stop with explanation and override instructions (`architecture.solutionTypeOverride = true`).\n\n---\n\n## Step 0.5: Decision Gate\n\nReads `agentspec.json.decisions[]`, filters to MVP-relevant decisions, categorizes as hard-block (`architecture`, `infrastructure`) or soft-warning (`integration`, `model`, `topic-implementation`). Hard blocks stop the build. Soft warnings proceed with recommended defaults pre-applied.\n\n---\n\n## Before Building — Enrichment Check + Knowledge Cache + Learnings\n\n### Enrichment-Aware Build\n\nIf the spec was created via the Agent Wizard and background enrichment ran (check `agentspec.json._enrichment`):\n- **Instructions**: Enrichment may have generated instructions via Claude Sonnet. Review them during Step 2 — if quality is sufficient, use as-is. If not, spawn PE to revise (not regenerate from scratch).\n- **Eval sets**: Enrichment may have generated eval test sets. Review during Step 4.5 — if coverage is sufficient, use as-is. QA validates and enhances rather than regenerating.\n- **Architecture scoring**: Enrichment ran deterministic scoring (build path, first-party agent matching, channel suggestions). These are pre-applied to the spec.\n- **Research flags**: Check `agentspec.json.recommendations[]` where `source === \"enrichment\"` — these are integrations the resolver couldn't match. May need live research or manual configuration.\n\n### Knowledge Cache + Learnings\n\n1. Read `knowledge\u002Fcache\u002Fapi-capabilities.md` — check `last_verified` date\n2. If stale (> 7 days), refresh via WebSearch + MS Learn\n3. Read `knowledge\u002Fpatterns\u002Fdataverse-patterns.md` for API call patterns\n4. Read `knowledge\u002Flearnings\u002Fbuild-methods.md` — check for creation precedents and known gotchas\n5. Update cache files if new findings\n\n## Route: Determine Build Mode\n\nRead `agentspec.json` -> `architecture.type`:\n\n| Value | Build Path |\n|-------|-----------|\n| `Single Agent` | Standalone Build (below) |\n| `Multi-Agent` | Multi-Agent Build (below) |\n| `Connected Agent` | Standalone Build + external connection notes |\n\n---\n\n## On-Demand Teammates During Build\n\nTwo teammates are available on-demand when issues arise (not spawned at build start — only when specific conditions trigger them). This keeps simple builds fast while making complex builds resilient.\n\n**Research Analyst** — spawned when tool configuration fails (connector not found, auth mode mismatch, unexpected parameters). RA searches official docs and community, reports correct name\u002Fauth\u002Falternatives. Lead applies the fix, updates spec + cache, dismisses RA.\n\n**Prompt Engineer** — spawned when instructions need adjustment after tools are configured (tool names differ, planned tool unavailable, action parameters changed, instructions exceed 8000 chars). PE uses GPT co-generation (`generate-instructions`) to produce and merge revised instructions. QA reviews, lead applies via LSP push, dismisses PE.\n\n## Step Failure Protocol (Build-Time Error Handling)\n\nWhen any build step fails (LSP push error, Dataverse 4xx\u002F5xx, connector mismatch, publish ConcurrencyVersionMismatch, eval Direct Line failure, flow build error), follow the 3-attempt protocol from `CLAUDE.md` → \"Error Handling\" — do NOT just retry with a \"different approach\":\n\n**Attempt 1 — research-driven retry:**\n1. **Query claude-mem first** — vector search the error message + step name + connector\u002Fmodel\u002Fcomponent name. Prior fixes for this exact pattern often exist. If found, prefer that fix over a fresh research cycle.\n2. Read `knowledge\u002Flearnings\u002F` topic file relevant to the failing step (`build-methods.md`, `connectors.md`, `topics-triggers.md`).\n3. WebSearch for error string + \"Copilot Studio\".\n4. MS Learn MCP for official troubleshooting.\n5. Read back the API state (Dataverse query, LSP pull, `pac copilot list`) to confirm what actually happened.\n6. Retry with the researched approach.\n\n**Attempt 2 — superpowers 4-phase debug (NOT a generic retry):**\nIf Attempt 1 fails, do NOT retry the same operation with another small change. Invoke the superpowers debugging skill explicitly:\n1. **Hypothesize** — enumerate candidate root causes from the layer set: `auth-token | payload-schema | API-contract | connector-config | model-availability | tenant-policy | timing | concurrency | LSP-Dataverse-divergence`. List 3-5 hypotheses with the evidence supporting each.\n2. **Reproduce** — produce a minimal repro outside the build pipeline. For Dataverse failures, run the same `curl` directly. For LSP push failures, do a dry-run pull-then-push on a clean copy. Confirm the failure is deterministic.\n3. **Isolate** — design ONE discriminating test per top hypothesis. Examples: \"if it's auth, fresh token retry succeeds\"; \"if it's schema, payload-only modification reproduces it\"; \"if it's concurrency, sequential push succeeds\". Run the tests. Narrow to one layer.\n4. **Fix** — apply the targeted fix. Verify via API read-back. Log the isolated cause + fix to `knowledge\u002Flearnings\u002Fbuild-methods.md` (or the relevant topic file) so claude-mem will surface it on Attempt 1 next time.\n\n**Attempt 3 — escalate to user:**\nIf superpowers-debug doesn't isolate the cause in one cycle, escalate. Include: the hypothesis tree, what was tested, what remains uncertain, and the proposed next step (user manual MCS UI check, fresh tenant test, etc.).\n\n**Failure budget rules:**\n- A single build can absorb the 3-attempt protocol on at most TWO distinct steps before escalating the build itself.\n- Same-step third failure → escalate immediately, do not loop.\n- Always emit `##PROGRESS##` markers with `status: \"failed\"` and a `detail` summarizing which attempt was reached.\n\n---\n\n## Standalone Build (Single Agent)\n\n### Dataverse API Shorthand\n\nAll Dataverse calls use buildStatus fields from Step 0.9:\n\n```bash\nTOKEN=$(az account get-access-token --resource \u003CbuildStatus.dataverseUrl> --query accessToken -o tsv)\nDV=\"\u003CbuildStatus.dataverseUrl>\"\nBOT=\"\u003CbuildStatus.mcsAgentId>\"\nGPT=\"\u003CbuildStatus.gptComponentId>\"\n```\n\n**Publish + verify pattern:**\n```bash\ncurl -s -X POST \"$DV\u002Fapi\u002Fdata\u002Fv9.2\u002Fbots($BOT)\u002FMicrosoft.Dynamics.CRM.PvaPublish\" \\\n  -H \"Authorization: Bearer $TOKEN\" -H \"Content-Type: application\u002Fjson\" -d '{}'\nsleep 5\n# Query WITHOUT $select (synchronizationstatus returns null with $select)\ncurl -s \"$DV\u002Fapi\u002Fdata\u002Fv9.2\u002Fbots($BOT)\" -H \"Authorization: Bearer $TOKEN\" | node -e \"\nlet d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>{\n  const data=JSON.parse(d);\n  const ss=JSON.parse(data.synchronizationstatus||'{}');\n  const status=(ss.lastFinishedPublishOperation||{}).status||'pending';\n  console.log('Publish status: '+status);\n})\"\n```\n\n**Description PATCH:** Now handled automatically by `mcs-lsp.js push` (patches lines 1-2 of GptComponent `data` field after LSP sync).\n\n### Step 0: Resume Detection & Environment Verification\n\nRead `agentspec.json.buildStatus.completedSteps`. If the array has entries, this is a resumed build — log which steps will be skipped. Mapping: `\"created\"` -> skip Step 1, `\"instructions\"` -> skip Step 2 instructions, `\"knowledge\"` -> skip Step 2 knowledge, `\"tools\"` -> skip Step 3 tools, `\"model\"` -> skip Step 3 model, `\"topics\"` -> skip Step 4. Step 5 (publish) re-runs on every build because it's cheap and ensures latest state.\n\n### Step 1: Find or Create Agent\n\nCheck for existing agent before creating, to prevent duplicates on build resume or session restart.\n\n**1a.** Check `agentspec.json.buildStatus.mcsAgentId` — if set, verify via `pac copilot list`. If found, skip creation. If not found (deleted), clear ID and proceed.\n\n**1b.** If no ID, search `pac copilot list` for matching `displayName`. If found, store ID and skip creation.\n\n**1c.** Create new agent via Dataverse POST + PvaProvision:\n1. POST `bots` with:\n   - `name`, `schemaname`, `language: 1033`, `runtimeprovider: 0`\n   - `authenticationmode: 1` (Integrated — \"Authenticate with Microsoft\")\n   - `authenticationtrigger: 1` (AsNeeded)\n   - `configuration` JSON including `GenerativeAIRecognizer` and `contentModeration: \"Medium\"`\n   - Example configuration: `{ settings: { GenerativeActionsEnabled: true }, aISettings: { model: { modelNameHint: \"GPT5Auto\" }, contentModeration: \"Medium\" }, recognizer: { kind: \"GenerativeAIRecognizer\" } }`\n2. POST `PvaProvision` bound action\n3. Wait for `statuscode` to transition to `Provisioned(1)` (~5-15s)\n4. PATCH bot `name` field (LSP push updates GptComponent `displayName` but not the bot entity `name`)\n\n**Fallback:** `pac copilot create` (requires template extraction first).\n\n**1d.** Persist `mcsAgentId` to `agentspec.json.buildStatus` immediately. Add `\"created\"` to `completedSteps`.\n\n**1f. Flow Designer auto-spawn:** After the agent shell exists, scan `agentspec.json.architecture.solutionType` (and `buildPath`). If it matches `flow`, `hybrid`, or `automation`, spawn `flow-designer` (`Agent({ subagent_type: \"flow-designer\", isolation: \"worktree\", ... })`) to design Power Automate flow specs in parallel with Step 2-4. FD writes `flow-spec.md` to `Build-Guides\u002F\u003Cproject>\u002Fagents\u002F\u003Cname>\u002Fflows\u002F`. Skipped silently when solutionType is pure agent.\n\n#### 1e. Clone Agent Workspace (LSP)\n\n```bash\nnode tools\u002Fmcs-lsp.js clone \\\n  --workspace \"Build-Guides\u002F{projectId}\u002Fagents\u002F{agentId}\u002Fworkspace\" \\\n  --agent-id \"\u003CmcsAgentId>\" --agent-name \"\u003CdisplayName>\" \\\n  --env-id \"\u003CenvironmentId>\" --dataverse-url \"\u003CdataverseUrl>\" --gateway-url \"\u003CgatewayUrl>\"\n```\n\nStore the **agent subfolder** (the one containing `.mcs\u002Fconn.json`) in `buildStatus.workspacePath` — not the parent directory. Push\u002Fpull commands need the subfolder path.\n\nSkip if `buildStatus.workspacePath` exists and the directory has `.mcs\u002Fconn.json`.\n\n#### Pre-push Validation (run before every LSP push)\n\nBefore running `mcs-lsp.js push`:\n1. Workspace exists: `\u003CworkspacePath>\u002F.mcs\u002Fconn.json` present\n2. `agent.mcs.yml` line 1: starts with `# Name:` and is not `# Name: default`\n3. `agent.mcs.yml` line 2: is not `# default` (has actual description)\n4. Conversation starters: every entry has both `title` and `text` (missing title causes silent publish failure)\n5. Instructions: \u003C 8000 chars\n6. Freshness: if last pull was > 30 min ago, pull first to avoid ConcurrencyVersionMismatch\n\n`mcs-lsp.js push` now automatically patches `botcomponent.description`, `botcomponent.name`, and comment headers via Dataverse API after LSP sync.\n\n### Steps 2-4: Parallel Dispatch (Instructions, Knowledge, Tools, Topics)\n\nAfter Step 1 completes (agent shell exists in MCS), Steps 2-4 run **in parallel** to compress the build. Dispatch all four work items in a single message with multiple Agent tool calls:\n\n| Work item | Owner | Isolation | Output written to |\n|-----------|-------|-----------|-------------------|\n| Instructions (Step 2b) | Prompt Engineer (sub-agent) | `worktree` | `agent.mcs.yml` `instructions:` field |\n| Knowledge (Step 2 knowledge) | Lead | — | `knowledge\u002F*.mcs.yml` + Dataverse uploads |\n| Tools \u002F MCP (Step 3) | Lead | — | `actions\u002F*.mcs.yml` |\n| Topics (Step 4) | Topic Engineer (sub-agent) | `worktree` | `topics\u002F*.mcs.yml` + Gateway create-topic |\n\nLead-driven items (knowledge, tools) don't need worktree isolation because the lead serializes its own writes. Sub-agent items (PE, TE) MUST run in worktrees because they both touch `agent.mcs.yml` and `agentspec.json` adjacent paths.\n\nAfter all four return, the lead reads each output, merges as needed, and proceeds to Step 5 (publish). Step 5 is gated on every parallel item completing.\n\n**Resume behavior:** Each sub-step has its own `completedSteps` checkpoint. If `\"instructions\"` is already in `completedSteps`, the PE dispatch is skipped — same for `\"knowledge\"`, `\"tools\"`, `\"topics\"`.\n\n### Step 2: Configure Agent Metadata, Instructions & Knowledge\n\n**Skip check:** If `\"instructions\"` and `\"knowledge\"` are both in `completedSteps`, skip this entire step.\n\n**2a. Description & Starters:** Edit `agent.mcs.yml` — set lines 1-2 (name, description metadata) and `conversationStarters` (each entry needs both `title` and `text`). Push via LSP.\n\n**2b. Instructions:** Edit `agent.mcs.yml` `instructions:` field. Run instruction-capability alignment check first (verify MVP capabilities are addressed, future capabilities are not). Push via LSP. Checkpoint: add `\"instructions\"` to `completedSteps`.\n\n**Knowledge:** Create `.mcs.yml` files in `knowledge\u002F` folder for SharePoint sites and URLs. Use Dataverse API for file uploads (PDF, DOCX). Phase filter: only MVP entries. Checkpoint: add `\"knowledge\"` to `completedSteps`.\n\n**Initial Publish:** `pac copilot publish --bot \u003Cbot-id>`\n\n**On-demand PE trigger:** After Step 3 configures tools, if tool names differ from spec, spawn PE to adjust instructions.\n\n### Before Step 3: Consult Connector & Integration Learnings\n\nRead `knowledge\u002Flearnings\u002Fconnectors.md` and `integrations.md` — look for connector name mismatches, auth gotchas, known workarounds.\n\n### Step 3: Configure Tools & Model\n\n**Skip check:** If `\"tools\"` and `\"model\"` are both in `completedSteps`, skip this step.\n\n**3a. Model Selection:** Default to `GPT5Auto` (GPT-5 Auto — dynamically routes between general and reasoning). Edit `agent.mcs.yml` -> `aISettings.model.modelNameHint: GPT5Auto`. Only change if spec specifies a different model or the environment doesn't support preview models. Check available models via `island-client.js get-models`. Checkpoint: add `\"model\"`.\n\n**3b. Settings (type: \"setting\" integrations):** Patch `bot.configuration` via Dataverse. Always set: `GenerativeActionsEnabled: true`, `recognizer: GenerativeAIRecognizer`. Per-spec: web browsing, model knowledge, content moderation.\n\n**3c. Tool\u002FConnector\u002FMCP Configuration:**\n\n**Work IQ first:** For any M365 data integration (email, calendar, teams, sharepoint, onedrive, user profile, files, search), add Work IQ from the agent overview page. This adds 2 MCP servers that cover everything:\n\n- **Work IQ Copilot** (`mcp_M365Copilot`) — cross-M365 search and actions for mail, calendar, teams, sharepoint, onedrive, files, everything\n- **Work IQ User** (`mcp_MeServer`) — people, org chart, manager, direct reports\n\nNo need to add individual Mail, Calendar, Teams, SharePoint servers separately. These 2 replace all individual M365 MCP servers and connectors. Requires M365 Copilot license. Status: Preview (Mar 2026).\n\n1. Auto-discover connection refs: `node tools\u002Fadd-tool.js discover-connections --dataverse-url \u003Curl>`\n2. Check if `shared_a365mcpservers` connection exists (covers Work IQ)\n3. Match discovered connections to spec integrations — prefer Work IQ matches from the resolver's `workiqRecommended` field\n4. For matched: write YAML action files to `workspace\u002Factions\u002F`, push via LSP\n5. For unmatched: guide user to add Work IQ from overview page in MCS UI, re-discover, then write YAML + push\n\n**Gaps (use connectors instead):** Planner, Excel, Approvals, PowerPoint have no Work IQ equivalent — use Power Platform connectors.\n\n**When NOT to use Work IQ:** Non-M365 integrations (Dynamics 365, Dataverse, Fabric, third-party) use their own MCP servers or connectors as before.\n\nCheckpoint: add `\"tools\"` to `completedSteps`. Verify via LSP pull that `actions\u002F` has all expected tools.\n\n### Before Step 4: Consult Topic & Trigger Learnings\n\nRead `knowledge\u002Flearnings\u002Ftopics-triggers.md` — look for YAML patterns, adaptive card gotchas, node type issues.\n\n### Step 4: Author Topics (LSP Push)\n\n**Skip check:** If `\"topics\"` is in `completedSteps`, skip this step.\n\nUse **Topic Engineer** for validated YAML (dual model co-generation for 3+ node topics). Phase filter: only MVP topics. Topic type filter: only `custom` or `system` (customized) — `generative` topics are handled by orchestration, no YAML needed.\n\nFor each MVP custom\u002Fsystem topic:\n1. TE generates topic definition (trigger phrases, actions, description)\n2. QA reviews definitions\n3. Create via Gateway API (required — LSP push does not produce renderable new topics):\n   ```bash\n   node tools\u002Fisland-client.js create-topic --env \u003CenvId> --bot \u003CbotId> --topic-file \u003Cpath>\n   ```\n4. For adaptive card topics: create with text placeholder via Gateway, pull workspace, edit YAML to add `SendMessage` + `AdaptiveCardTemplate`, push via LSP (LSP can update existing topics safely)\n5. For system topic customization: edit in workspace, push via LSP\n6. **Conversation Start welcome card (ALWAYS):** Replace the default plain-text ConversationStart with an adaptive card welcome. Use `welcome-card.yaml` template — fill `{{AGENT_NAME}}`, `{{WELCOME_MESSAGE}}`, and capability action buttons from agentspec.json capabilities. Write to `workspace\u002FAgent\u002Ftopics\u002FConversationStart.mcs.yml`, then push via LSP (system topic update, not new topic creation). This is not optional — every agent gets a welcome card.\n7. Available adaptive card styles for topics (see `knowledge\u002Fpatterns\u002Ftopic-patterns\u002F`): `welcome-card.yaml` (welcome), `adaptive-card.yaml` (data display + form), `table-list-card.yaml` (tables\u002Flists), `carousel-card.yaml` (multi-card), `status-card.yaml` (progress\u002Fstatus), `approval-card.yaml` (approve\u002Freject), `confirmation-card.yaml` (review before submit), `feedback-card.yaml` (thumbs up\u002Fdown). Choose the style that best fits each topic's purpose.\n\nDo not use `mcs-lsp.js push` to create new custom topics because the LSP skips internal MCS registration (NLU trigger indexing, compilation). Gateway API `BotComponentInsert` handles all registration automatically.\n\nCheckpoint: add `\"topics\"` to `completedSteps`.\n\n### Step 4.4: Power Automate Flow Build\n\nRuns only when `agentspec.json.flows[]` has at least one entry. The agent's logical name and Dataverse environment must already exist (Step 1 done), and topic YAML must already be pushed because flows are registered to the agent as `InvokeFlowTaskAction` in topics.\n\n**Order of operations** — handled by `tools\u002Fflow-build.js`:\n\n1. Validate `flows[]` (delegates to `app\u002Flib\u002Fflow-spec.js`). Fast-fail on schema errors.\n2. Topo-sort: `kind=ai-tool` first, then `kind=agent-flow` (which can reference ai-tools by `name`).\n3. For each flow in order:\n   - **Plan**: skip if `id` set and `status=='published'` (Phase 5 will add content-hash drift detection).\n   - **Create**: `flowManager.createAIFlow` for ai-tool (category=7) or `flowManager.createFlow` for agent-flow (category=5, modernflowtype=1). Auto-derives `environment.name` from the Dataverse org.\n   - **Resolve cross-refs**: `aiFlowRef` → ai-tool's `id` (which exists because topo sort built it first).\n   - **Publish**: `flowManager.publishFlow` calls `POST \u002FPublishComponent?ActivateFlowOnPublish=true` — single bound action publishes the component AND activates runtime.\n   - **Persist**: write `id`, `status`, `lastSyncedAt` back to `agentspec.json.flows[i]`.\n4. Failure isolation: a flow that fails marks `status='failed'` + `lastBuildError`, and execution continues with other independent flows.\n\n```bash\n# Plan-only (no API calls) — useful before the first build\nnode tools\u002Fflow-build.js plan --spec Build-Guides\u002F\u003Cproject>\u002Fagents\u002F\u003Cagent>\u002Fagentspec.json\n\n# Build all flows\nnode tools\u002Fflow-build.js run \\\n  --spec Build-Guides\u002F\u003Cproject>\u002Fagents\u002F\u003Cagent>\u002Fagentspec.json \\\n  --org \"$DV\"\n\n# Build a single flow (e.g. after a fix)\nnode tools\u002Fflow-build.js run --spec \u003Cagentspec> --org \"$DV\" --only \u003CflowName>\n```\n\n**Verify-then-mark**: after the run, query Dataverse for each `flows[i].id` and confirm `componentstate=0` (Published) and `statecode=1` (Activated). The CLI does this implicitly via the `publishFlow` round-trip; an explicit read-back is added in Phase 5.\n\n**Agent-side tool registration**: registering an agent-flow as a callable tool (`actions\u002F\u003Cname>.mcs.yml` with `kind: TaskDialog, action: { kind: InvokeFlowTaskAction, flowId }`) is still authored as part of Step 4 (topics) — the flow build produces the `flowId` that those YAML files reference. Re-push the topic via `mcs-lsp.js` after the flow build if the YAML referenced `\u003CflowId-pending>` or similar placeholder.\n\nCheckpoint: add `\"flows\"` to `completedSteps` once every `flows[i]` is either `status='published'` or `status='failed'` (with the failure recorded — silent skip is forbidden).\n\n### Step 4.5: Post-Build Eval\n\n**Check:** If agent uses MCP servers with user-delegated auth, skip automated eval (Direct Line can't authenticate). Generate test cases for manual testing instead.\n\n**Auto mode (Direct Line):** Acquire token, run boundaries set (target 100%), run quality set (target 85%), write results to `agentspec.json.evalSets[].tests[].lastResult`.\n\n**Manual mode (Gateway API):** Upload eval sets via `island-client.js upload-evals`, run via `run-eval`, present summary. User checks results in MCS or runs `\u002Fmcs-eval` later.\n\nNo iterative boundaries\u002Fquality\u002Fedge-cases loop during build. Build is single-pass. User runs `\u002Fmcs-fix` for post-deployment issues.\n\n### Step 5: Publish (Dataverse PvaPublish)\n\nRe-runs on every build (even resume) because publishing is cheap and ensures latest state.\n\n```bash\ncurl -s -X POST \"$DV\u002Fapi\u002Fdata\u002Fv9.2\u002Fbots($BOT)\u002FMicrosoft.Dynamics.CRM.PvaPublish\" \\\n  -H \"Authorization: Bearer $TOKEN\" -H \"Content-Type: application\u002Fjson\" -d '{}'\n```\n\nVerify via `synchronizationstatus` (not just HTTP 200): query bot without `$select`, parse `lastFinishedPublishOperation.status`. Poll up to 6 attempts at 5s intervals. Also check `publishedon` is today.\n\nCommon failures: `MissingRequiredProperty: Title` (starter without `title`), `ConcurrencyVersionMismatch` (stale workspace), `InvalidComponent` (malformed YAML).\n\nCheckpoint: add `\"published\"` to `completedSteps` after `synchronizationstatus` shows `\"Succeeded\"`.\n\n### Step 5.5: QA Build Validation Gate\n\nAfter publish, spawn QA Challenger for formal validation. The lead collects reconciliation snapshots, runs automated drift detection (`drift-detect.py`), and QA analyzes everything: spec-vs-actual comparison, cross-reference validation, and deviation impact assessment. QA writes `qa-validation.md` with a verdict of PASS \u002F PASS WITH CAVEATS \u002F FAIL.\n\n> Full QA protocol: see reference\u002Fqa-validation-gate.md\n\n### Step 5.6: GPT Build Review\n\nAfter QA validation, fire GPT-5.5 via `multi-model-review.js`: `review-brief`, `review-instructions`, and per-topic `review-topics`. GPT findings merge with QA verdict (union of findings, stricter wins). If GPT finds a critical issue QA missed, escalate to user before writing buildStatus. If GPT is unavailable, proceed with QA verdict alone.\n\n### Step 6: Finalize agentspec.json buildStatus\n\nWrite the complete buildStatus. Most fields were written incrementally during checkpoints — this step ensures the final state is clean:\n\n```json\n{\n  \"buildStatus\": {\n    \"status\": \"published\",\n    \"lastBuild\": \"2026-02-18T...\",\n    \"mcsAgentId\": \"\u003Cbot-id>\",\n    \"environment\": \"\u003Cenv-name>\",\n    \"account\": \"\u003Caccount-label>\",\n    \"accountId\": \"\u003Csession-config-account-id>\",\n    \"publishedAt\": \"2026-02-18T...\",\n    \"completedSteps\": [\"created\", \"instructions\", \"knowledge\", \"tools\", \"model\", \"topics\", \"critical-gate\", \"capability-iteration\", \"edge-cases\", \"published\"],\n    \"lastCompletedStep\": \"published\",\n    \"lastError\": null\n  }\n}\n```\n\n---\n\n## Multi-Agent Build\n\nBuild specialists first, then orchestrator. Each specialist follows the standalone build flow with specialist-focused instructions and sharing enabled. The orchestrator connects to all specialists via Island Gateway API.\n\n> Full multi-agent protocol: see reference\u002Fmulti-agent-build.md\n\n---\n\n## End-of-Build Reconciliation\n\nAfter all changes, walk the spec's MVP-scoped component list and snapshot each item: agent name, model, instructions, knowledge sources, tools, triggers, publish status, (multi-agent) specialist connections and sharing. Collect deferred items list. Then spawn QA Challenger (Step 5.5) with the snapshot data, agentspec.json, and deferred items list.\n\n## Output: Build Summary Report\n\nAfter reconciliation, generate two outputs:\n\n### Terminal Output\n\n```\n## Build Complete: [Agent Name]\n\n**Status:** Published | **Environment:** [env] | **Account:** [account]\n**QA Validation:** PASS ({N}\u002F{N} items match, {M} cross-ref issues — see qa-validation.md)\n**Eval Sets:** boundaries {X}% | quality {X}% | edge-cases {X}%\n**Capabilities:** {N} passing, {M} failing, {K} not tested\n**Deferred:** {J} future items (see build report Section 9)\n\nReport saved: Build-Guides\u002F{projectId}\u002Fagents\u002F{agentId}\u002Fbuild-report.md\n\n**Next:** Review the build report, share with customer for approval. Run \u002Fmcs-eval for standalone re-runs.\n```\n\n### Build Report File\n\nWrite a customer-shareable build report to `build-report.md` with 11 sections: overview, architecture, capabilities, tools, knowledge, topics\u002Ftriggers, key behaviors, open questions, spec-vs-actual changes, eval status, and next steps.\n\n> Full template: see reference\u002Fbuild-report-template.md\n\n---\n\n## Post-Build Learnings\n\nTier 1 (auto): bump confirmed counts for routine builds. Tier 2 (user-confirmed): deviations, workarounds, discoveries. See `reference\u002Flearnings-capture.md` and `.claude\u002Frules\u002Flearnings-system.md`.\n",{"name":5,"description":7},"main","b7593fb57652591678d1aeb9bcc19738e903ffbe",".claude\u002Fskills\u002Fmcs-build",3,"https:\u002F\u002Fgithub.com\u002Fdayour\u002FMCS-Agent-Builder","https:\u002F\u002Fgithub.com\u002Fdayour","2026-11-08 11:20:11",{"source":8,"skillName":5,"commands":51,"prompt":61,"zipAvailable":62},[52,55,58],{"tool":53,"command":54},"npx","npx skills add dayour\u002FMCS-Agent-Builder --skill mcs-build",{"tool":56,"command":57},"bunx","bunx skills add dayour\u002FMCS-Agent-Builder --skill mcs-build",{"tool":59,"command":60},"pnpm","pnpm dlx skills add dayour\u002FMCS-Agent-Builder --skill mcs-build","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdayour\u002FMCS-Agent-Builder\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fmcs-build\u002FSKILL.md",true,[64,70,74,78,82],{"path":65,"resourceType":66,"resourceTypeDesc":67,"sizeBytes":68,"sourceHtmlUrl":69},"reference\u002Fauth-gate.md","REFERENCE","参考文档",4382,"https:\u002F\u002Fgithub.com\u002Fdayour\u002FMCS-Agent-Builder\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fmcs-build\u002Freference\u002Fauth-gate.md",{"path":71,"resourceType":66,"resourceTypeDesc":67,"sizeBytes":72,"sourceHtmlUrl":73},"reference\u002Fbuild-report-template.md",5479,"https:\u002F\u002Fgithub.com\u002Fdayour\u002FMCS-Agent-Builder\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fmcs-build\u002Freference\u002Fbuild-report-template.md",{"path":75,"resourceType":66,"resourceTypeDesc":67,"sizeBytes":76,"sourceHtmlUrl":77},"reference\u002Flearnings-capture.md",2790,"https:\u002F\u002Fgithub.com\u002Fdayour\u002FMCS-Agent-Builder\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fmcs-build\u002Freference\u002Flearnings-capture.md",{"path":79,"resourceType":66,"resourceTypeDesc":67,"sizeBytes":80,"sourceHtmlUrl":81},"reference\u002Fmulti-agent-build.md",3761,"https:\u002F\u002Fgithub.com\u002Fdayour\u002FMCS-Agent-Builder\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fmcs-build\u002Freference\u002Fmulti-agent-build.md",{"path":83,"resourceType":66,"resourceTypeDesc":67,"sizeBytes":84,"sourceHtmlUrl":85},"reference\u002Fqa-validation-gate.md",4474,"https:\u002F\u002Fgithub.com\u002Fdayour\u002FMCS-Agent-Builder\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fmcs-build\u002Freference\u002Fqa-validation-gate.md",[87,103,110,115,122,127],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":38},"01M6WTHH2JPKXM1JDRE55KC4A6","order-status","Read the packaged Copilot Studio agent definition, including messaging topics and boundaries, from the local plugin.","https:\u002F\u002Fgithub.com\u002Fdayour\u002FMCS-Agent-Builder\u002Fblob\u002Fmain\u002Fschema\u002Ffixtures\u002Finvalid\u002Fmodel-secret\u002Fskills\u002Forder-status\u002FSKILL.md",[],[94,95,36,96,35,97,98,99,100,21,101,102],"order status","status","plugin","messaging","read","local","agent definition","definition","topics",{"skillNo":104,"name":105,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":38},"01M6WTHE20Y6X94754CP3TAY1Y","level-pass","https:\u002F\u002Fgithub.com\u002Fdayour\u002FMCS-Agent-Builder\u002Fblob\u002Fmain\u002Fschema\u002Ffixtures\u002Finvalid\u002Flevel-status-failed\u002Fskills\u002Flevel-pass\u002FSKILL.md",[],[109,98,97,35,96,36,21,99,100,101,102],"level pass",{"skillNo":111,"name":105,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":38},"01M6WTHBZ5EY53QPYKREMEVHZK","https:\u002F\u002Fgithub.com\u002Fdayour\u002FMCS-Agent-Builder\u002Fblob\u002Fmain\u002Fschema\u002Ffixtures\u002Finvalid\u002Flevel-status-fail\u002Fskills\u002Flevel-pass\u002FSKILL.md",[],[109,101,102,21,100,99,98,97,36,35,96],{"skillNo":116,"name":117,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":38},"01M6WTH9AKX173Y69CJS3CZM5A","level-not-passing","https:\u002F\u002Fgithub.com\u002Fdayour\u002FMCS-Agent-Builder\u002Fblob\u002Fmain\u002Fschema\u002Ffixtures\u002Finvalid\u002Flevel-malformed\u002Fskills\u002Flevel-not-passing\u002FSKILL.md",[],[121,36,96,35,97,98,99,100,21,101,102],"level not passing",{"skillNo":123,"name":105,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":126,"publishedAt":38},"01M6WTH70Z5Z2JV26J9C1ZRYPS","https:\u002F\u002Fgithub.com\u002Fdayour\u002FMCS-Agent-Builder\u002Fblob\u002Fmain\u002Fschema\u002Ffixtures\u002Finvalid\u002Flevel-long-fence\u002Fskills\u002Flevel-pass\u002FSKILL.md",[],[109,100,36,96,35,97,98,99,21,101,102],{"skillNo":128,"name":105,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":129,"categories":130,"keywords":131,"publishedAt":38},"01M6WTH4ZSAJ8SADD803KY2DW0","https:\u002F\u002Fgithub.com\u002Fdayour\u002FMCS-Agent-Builder\u002Fblob\u002Fmain\u002Fschema\u002Ffixtures\u002Finvalid\u002Flevel-indented\u002Fskills\u002Flevel-pass\u002FSKILL.md",[],[109,96,35,97,98,99,100,21,101,102,36]]