{
  "nbformat": 4,
  "nbformat_minor": 5,
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.13.0"
    },
    "blog_metadata": {
      "topic": "Copilot harness in Foundry is the first agent feature I’d put in front of a governance board",
      "slug": "copilot-harness-in-foundry-is-the-first-agent-feature-i-d-pu",
      "generated_by": "LinkedIn Post Generator + Azure OpenAI",
      "generated_at": "2026-11-11T21:11:57.740Z"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Copilot harness in Foundry is the first agent feature I’d put in front of a governance board\n",
        "\n",
        "This notebook turns the blog post into a hands-on validation flow focused on governance controls for agent lifecycle events. It demonstrates how to model bounded execution, human approval thresholds, auditability, and redaction using simple Python examples inspired by the Copilot harness and Foundry governance discussion."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "%pip install -q pandas"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass, field, asdict\n",
        "from datetime import datetime\n",
        "from typing import List, Dict, Any\n",
        "import json\n",
        "import re\n",
        "import textwrap\n",
        "import pandas as pd"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Governance context and source links\n",
        "\n",
        "The core argument is that governance boards should review lifecycle control points before the next agent demo, not after a pilot has already created momentum. The key architectural idea is bounded execution: define what the agent may do, where it must pause, and who owns exceptions.\n",
        "\n",
        "Relevant references:\n",
        "- Microsoft Foundry Agent Service overview: https://learn.microsoft.com/en-us/azure/foundry/agents/overview\n",
        "- Agents powered by the GitHub Copilot Harness overview: https://learn.microsoft.com/en-us/microsoft-copilot-studio/agents-experience/overview\n",
        "- Step 1: Your First Agent: https://learn.microsoft.com/en-us/agent-framework/get-started/your-first-agent"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "governance_principles = {\n",
        "    \"approved_lane\": [\n",
        "        \"What actions are inside the approved lane\",\n",
        "        \"What actions require a human in the loop\",\n",
        "        \"What actions are flatly denied\",\n",
        "        \"Who owns the business outcome when the agent gets it wrong\"\n",
        "    ],\n",
        "    \"lifecycle_hooks\": [\n",
        "        \"session start\",\n",
        "        \"before tool run\"\n",
        "    ],\n",
        "    \"board_requirements\": [\n",
        "        \"specific tools the agent can invoke\",\n",
        "        \"decisions the agent can influence\",\n",
        "        \"escalation path\",\n",
        "        \"named owners\",\n",
        "        \"renewable approval\"\n",
        "    ]\n",
        "}\n",
        "\n",
        "df = pd.DataFrame(\n",
        "    [(k, \", \".join(v)) for k, v in governance_principles.items()],\n",
        "    columns=[\"Category\", \"Details\"]\n",
        ")\n",
        "\n",
        "df"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Example 1: Define a minimal governance policy pack\n",
        "\n",
        "This example creates a simple policy pack that captures allowed tools, blocked terms, prompt length limits, and tools that require human approval. It is a compact way to represent the bounded operating unit a governance board would want to review."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass, field\n",
        "from typing import List\n",
        "\n",
        "@dataclass\n",
        "class PolicyPack:\n",
        "    allowed_tools: List[str] = field(default_factory=lambda: [\"search_docs\", \"create_ticket\"])\n",
        "    blocked_terms: List[str] = field(default_factory=lambda: [\"password\", \"ssn\", \"secret\"])\n",
        "    max_prompt_chars: int = 500\n",
        "    require_human_approval_for: List[str] = field(default_factory=lambda: [\"delete_record\"])\n",
        "\n",
        "policy = PolicyPack()\n",
        "print(policy)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Example 2: Evaluate a user request against prompt, tool, and approval policies\n",
        "\n",
        "This example tests whether a request should be approved, denied, or flagged for human approval. It demonstrates the practical governance pattern from the post: classify every consequential tool call into a clear route."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass\n",
        "\n",
        "@dataclass\n",
        "class Decision:\n",
        "    allowed: bool\n",
        "    reason: str\n",
        "\n",
        "def evaluate_request(prompt: str, tool: str) -> Decision:\n",
        "    blocked_terms = {\"password\", \"ssn\", \"secret\"}\n",
        "    if len(prompt) > 500:\n",
        "        return Decision(False, \"Prompt too long\")\n",
        "    if any(term in prompt.lower() for term in blocked_terms):\n",
        "        return Decision(False, \"Sensitive term detected\")\n",
        "    if tool not in {\"search_docs\", \"create_ticket\", \"delete_record\"}:\n",
        "        return Decision(False, \"Tool not approved\")\n",
        "    if tool == \"delete_record\":\n",
        "        return Decision(False, \"Human approval required\")\n",
        "    return Decision(True, \"Approved\")\n",
        "\n",
        "print(evaluate_request(\"Create a ticket for laptop issue\", \"create_ticket\"))\n",
        "print(evaluate_request(\"Delete the employee record\", \"delete_record\"))\n",
        "print(evaluate_request(\"My password is Winter2026!\", \"search_docs\"))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Example 3: Session-start and pre-tool-run governance checks\n",
        "\n",
        "This example mirrors the blog post's pseudocode more directly. It shows how governance can establish operating context at session start and then enforce policy before a tool runs."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "APPROVED_TOOLS = {\"search_docs\", \"create_ticket\", \"delete_record\"}\n",
        "HUMAN_APPROVAL_TOOLS = {\"delete_record\"}\n",
        "BLOCKED_TERMS = {\"password\", \"ssn\", \"secret\"}\n",
        "\n",
        "def on_session_start(user_id: str, environment: str) -> dict:\n",
        "    if environment not in {\"prod\", \"test\"}:\n",
        "        return {\"allowed\": False, \"reason\": \"Unknown environment\"}\n",
        "    return {\n",
        "        \"allowed\": True,\n",
        "        \"policy_pack\": \"standard-enterprise\",\n",
        "        \"user_id\": user_id,\n",
        "        \"environment\": environment\n",
        "    }\n",
        "\n",
        "def before_tool_run(prompt: str, tool: str, session_context: dict) -> dict:\n",
        "    if not session_context.get(\"allowed\"):\n",
        "        return {\"decision\": \"deny\", \"reason\": \"Invalid session\"}\n",
        "    if len(prompt) > 500:\n",
        "        return {\"decision\": \"deny\", \"reason\": \"Prompt too long\"}\n",
        "    if any(term in prompt.lower() for term in BLOCKED_TERMS):\n",
        "        return {\"decision\": \"deny\", \"reason\": \"Sensitive term detected\"}\n",
        "    if tool not in APPROVED_TOOLS:\n",
        "        return {\"decision\": \"deny\", \"reason\": \"Tool not approved\"}\n",
        "    if tool in HUMAN_APPROVAL_TOOLS:\n",
        "        return {\"decision\": \"pause\", \"reason\": \"Human approval required\"}\n",
        "    return {\"decision\": \"proceed\", \"reason\": \"Approved\"}\n",
        "\n",
        "session = on_session_start(\"u123\", \"prod\")\n",
        "print(\"Session:\", session)\n",
        "print(\"Search decision:\", before_tool_run(\"Find the retention policy\", \"search_docs\", session))\n",
        "print(\"Delete decision:\", before_tool_run(\"Delete record 42\", \"delete_record\", session))\n",
        "print(\"Sensitive decision:\", before_tool_run(\"My SSN is 123-45-6789\", \"search_docs\", session))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Example 4: Wrap tool execution with a simple harness and immutable audit event\n",
        "\n",
        "This example adds audit logging to the decision path. The point is not just to block unsafe actions, but to create evidence a governance board can review later."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass, asdict\n",
        "from datetime import datetime\n",
        "import json\n",
        "\n",
        "@dataclass\n",
        "class AuditEvent:\n",
        "    timestamp: str\n",
        "    prompt: str\n",
        "    tool: str\n",
        "    decision: str\n",
        "\n",
        "def run_harness(prompt: str, tool: str) -> str:\n",
        "    decision = \"Approved\" if tool == \"search_docs\" else \"Blocked\"\n",
        "    event = AuditEvent(datetime.utcnow().isoformat(), prompt, tool, decision)\n",
        "    print(json.dumps(asdict(event), separators=(\",\", \":\")))\n",
        "    return \"Executed safely\" if decision == \"Approved\" else \"Execution denied\"\n",
        "\n",
        "print(run_harness(\"Find the retention policy\", \"search_docs\"))\n",
        "print(run_harness(\"Delete the customer record\", \"delete_record\"))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Example 5: Record a lifecycle decision as an audit event\n",
        "\n",
        "This example follows the blog post's audit pseudocode more closely. It records who initiated the action, which tool was involved, and why the decision was made."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass, asdict\n",
        "from datetime import datetime\n",
        "import json\n",
        "\n",
        "@dataclass\n",
        "class AuditEvent:\n",
        "    timestamp: str\n",
        "    user_id: str\n",
        "    tool: str\n",
        "    decision: str\n",
        "    reason: str\n",
        "\n",
        "def record_decision(user_id: str, tool: str, decision: str, reason: str) -> None:\n",
        "    event = AuditEvent(\n",
        "        timestamp=datetime.utcnow().isoformat(),\n",
        "        user_id=user_id,\n",
        "        tool=tool,\n",
        "        decision=decision,\n",
        "        reason=reason\n",
        "    )\n",
        "    print(json.dumps(asdict(event), separators=(\",\", \":\")))\n",
        "\n",
        "record_decision(\"u123\", \"delete_record\", \"pause\", \"Human approval required\")\n",
        "record_decision(\"u456\", \"search_docs\", \"proceed\", \"Approved\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Example 6: Redact obvious sensitive values before logs or model context are persisted\n",
        "\n",
        "This example demonstrates a basic data protection control. The blog post emphasizes that lifecycle hooks are useful, but they do not replace enterprise decisions about redaction, retention, and data handling."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import re\n",
        "\n",
        "def redact(text: str) -> str:\n",
        "    text = re.sub(r\"\\b\\d{3}-\\d{2}-\\d{4}\\b\", \"[REDACTED_SSN]\", text)\n",
        "    text = re.sub(r\"(?i)password\\s*[:=]\\s*\\S+\", \"password=[REDACTED]\", text)\n",
        "    return text\n",
        "\n",
        "sample = \"User shared SSN 123-45-6789 and password=Winter2026!\"\n",
        "print(redact(sample))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Example 7: Simulate bounded execution routes across multiple requests\n",
        "\n",
        "This notebook-friendly simulation classifies requests into proceed, pause, or deny. It makes the governance model visible and testable across a small batch of scenarios."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "requests = [\n",
        "    {\"user_id\": \"u100\", \"environment\": \"prod\", \"prompt\": \"Find the retention policy\", \"tool\": \"search_docs\"},\n",
        "    {\"user_id\": \"u101\", \"environment\": \"prod\", \"prompt\": \"Create a support ticket for VPN issue\", \"tool\": \"create_ticket\"},\n",
        "    {\"user_id\": \"u102\", \"environment\": \"prod\", \"prompt\": \"Delete record 42\", \"tool\": \"delete_record\"},\n",
        "    {\"user_id\": \"u103\", \"environment\": \"prod\", \"prompt\": \"My password is Secret123\", \"tool\": \"search_docs\"},\n",
        "    {\"user_id\": \"u104\", \"environment\": \"dev\", \"prompt\": \"Find onboarding docs\", \"tool\": \"search_docs\"},\n",
        "    {\"user_id\": \"u105\", \"environment\": \"prod\", \"prompt\": \"Run payroll export\", \"tool\": \"export_payroll\"}\n",
        "]\n",
        "\n",
        "results = []\n",
        "for req in requests:\n",
        "    session = on_session_start(req[\"user_id\"], req[\"environment\"])\n",
        "    decision = before_tool_run(req[\"prompt\"], req[\"tool\"], session)\n",
        "    results.append({\n",
        "        \"user_id\": req[\"user_id\"],\n",
        "        \"environment\": req[\"environment\"],\n",
        "        \"tool\": req[\"tool\"],\n",
        "        \"decision\": decision[\"decision\"],\n",
        "        \"reason\": decision[\"reason\"]\n",
        "    })\n",
        "\n",
        "pd.DataFrame(results)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Example 8: Summarize decisions for governance review\n",
        "\n",
        "A governance board does not need more dashboards for their own sake; it needs evidence. This example aggregates decision outcomes so reviewers can quickly see where approvals, denials, and pauses are occurring."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "results_df = pd.DataFrame(results)\n",
        "summary = results_df.groupby([\"decision\", \"reason\"]).size().reset_index(name=\"count\")\n",
        "summary.sort_values([\"decision\", \"count\"], ascending=[True, False])"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Example 9: Represent the governance flow from the blog as structured data\n",
        "\n",
        "The original post included Mermaid diagrams. Since this notebook uses Python code cells, this example converts the flow into structured steps that can be inspected or exported."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "flow_steps = [\n",
        "    (1, \"User asks Copilot\"),\n",
        "    (2, \"Copilot Harness\"),\n",
        "    (3, \"Policy Pack\"),\n",
        "    (4, \"Prompt + Tool + Data Checks\"),\n",
        "    (5, \"Allowed?\"),\n",
        "    (6, \"If no: Block / Redact / Escalate\"),\n",
        "    (7, \"If yes: Execute Approved Tooling\"),\n",
        "    (8, \"Log Inputs, Outputs, Decisions\"),\n",
        "    (9, \"Review by Governance Board\")\n",
        "]\n",
        "\n",
        "pd.DataFrame(flow_steps, columns=[\"Step\", \"Description\"])"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Example 10: Board-level approval checklist for a production agent\n",
        "\n",
        "This final validation example turns the blog's governance model into a concrete checklist. It can be used as a lightweight readiness review before production approval."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "board_checklist = {\n",
        "    \"specific_tools_listed\": True,\n",
        "    \"decision_surfaces_documented\": True,\n",
        "    \"escalation_path_defined\": True,\n",
        "    \"named_business_owner\": \"Director of Operations\",\n",
        "    \"named_platform_owner\": \"Platform Engineering Lead\",\n",
        "    \"named_risk_owner\": \"Enterprise Risk Manager\",\n",
        "    \"renewable_approval_triggered_by\": [\n",
        "        \"new tools\",\n",
        "        \"expanded authority\",\n",
        "        \"new data domains\",\n",
        "        \"changed operational context\",\n",
        "        \"new agent-to-agent dependencies\"\n",
        "    ]\n",
        "}\n",
        "\n",
        "print(json.dumps(board_checklist, indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Summary\n",
        "\n",
        "The main takeaway is that lifecycle hooks are valuable because they create governable control surfaces: session-start context, pre-tool-run checks, approval routing, and auditable decisions. They do not solve identity, telemetry, release discipline, or data protection by themselves, but they provide a practical place to enforce those policies.\n",
        "\n",
        "## Next Steps\n",
        "\n",
        "- Inventory your agent's tools and classify consequence levels.\n",
        "- Define which actions proceed, pause for approval, or are denied.\n",
        "- Add session-start and pre-tool-run controls to your implementation.\n",
        "- Log every decision path with enough detail for audit and incident review.\n",
        "- Assign business, platform, and risk owners before production approval.\n",
        "- Test exception paths, approval latency, identity design, and cross-agent ownership boundaries."
      ]
    }
  ]
}