{
  "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": "What Microsoft 365 Copilot for U.S. Government Reveals About Enterprise-Grade AI Controls",
      "slug": "what-microsoft-365-copilot-for-u-s-government-reveals-about-",
      "generated_by": "LinkedIn Post Generator + Azure OpenAI",
      "generated_at": "2026-08-10T19:15:08.010Z"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# What Microsoft 365 Copilot for U.S. Government Reveals About Enterprise-Grade AI Controls\n",
        "\n",
        "This notebook turns the blog post into hands-on validation exercises focused on three enterprise AI control themes: boundary, gate, and evidence. The examples are simplified, but they help test the operating model behind deployment boundaries, policy enforcement, retrieval controls, redaction, and auditability."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "%pip install pandas"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass, asdict\n",
        "import json\n",
        "import re\n",
        "from datetime import datetime, timezone\n",
        "import pandas as pd"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Control map and architecture boundary\n",
        "\n",
        "The blog argues that enterprise-grade AI starts with a visible boundary map. This cell converts the architecture narrative into structured Python data so teams can inspect the control path and validate where decisions are enforced and recorded."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "architecture_flow = {\n",
        "    \"nodes\": [\n",
        "        \"User Prompt in M365 App\",\n",
        "        \"Copilot Orchestrator\",\n",
        "        \"Identity & Conditional Access\",\n",
        "        \"Policy Evaluation\",\n",
        "        \"Grounding via Microsoft Graph\",\n",
        "        \"LLM Inference Boundary\",\n",
        "        \"Response Filtering & Audit\",\n",
        "        \"User Response\"\n",
        "    ],\n",
        "    \"policy_dependencies\": [\n",
        "        \"Sensitivity Labels\",\n",
        "        \"DLP Policies\",\n",
        "        \"Retention & eDiscovery\",\n",
        "        \"Government Cloud Controls\"\n",
        "    ]\n",
        "}\n",
        "\n",
        "boundary_map = {\n",
        "    \"tenant_in_scope\": \"example-tenant\",\n",
        "    \"enabled_native_experiences\": [\"M365 Chat\", \"Word\", \"Outlook\", \"Teams\"],\n",
        "    \"custom_agents\": [\"HR Agent\", \"Legal Intake Agent\", \"Service Ops Agent\"],\n",
        "    \"data_sources\": [\"Microsoft Graph\", \"SharePoint\", \"Exchange\", \"Teams\"],\n",
        "    \"external_extensions\": [\"Copilot Studio\", \"Line-of-business API\", \"Integrated apps\"]\n",
        "}\n",
        "\n",
        "print(\"Architecture flow:\")\n",
        "for i, node in enumerate(architecture_flow[\"nodes\"], start=1):\n",
        "    print(f\"{i}. {node}\")\n",
        "\n",
        "print(\"\\nPolicy dependencies:\")\n",
        "for dep in architecture_flow[\"policy_dependencies\"]:\n",
        "    print(f\"- {dep}\")\n",
        "\n",
        "print(\"\\nBoundary map:\")\n",
        "print(json.dumps(boundary_map, indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Residency and routing as an enforceable control\n",
        "\n",
        "The blog emphasizes that geography must be configurable and testable, not just described in slides. This example models routing as a policy decision: approved requests stay within the allowed boundary, and disallowed requests fail fast."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "def route_request(cloud: str, region: str) -> str:\n",
        "    approved = {\n",
        "        \"USGov\": {\"us\"},\n",
        "        \"Commercial\": {\"us\", \"eu\", \"apac\"},\n",
        "    }\n",
        "    if region not in approved.get(cloud, set()):\n",
        "        raise ValueError(f\"Region {region} not permitted for {cloud}\")\n",
        "    return f\"routed:{cloud}:{region}\"\n",
        "\n",
        "print(route_request(\"USGov\", \"us\"))\n",
        "\n",
        "scenarios = [\n",
        "    (\"USGov\", \"us\"),\n",
        "    (\"Commercial\", \"eu\"),\n",
        "    (\"USGov\", \"eu\"),\n",
        "]\n",
        "\n",
        "results = []\n",
        "for cloud, region in scenarios:\n",
        "    try:\n",
        "        outcome = route_request(cloud, region)\n",
        "        results.append({\"cloud\": cloud, \"region\": region, \"status\": \"allowed\", \"detail\": outcome})\n",
        "    except Exception as e:\n",
        "        results.append({\"cloud\": cloud, \"region\": region, \"status\": \"blocked\", \"detail\": str(e)})\n",
        "\n",
        "print(pd.DataFrame(results))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Feature gating before AI execution\n",
        "\n",
        "A core claim in the post is that publishing and execution should be gated by policy. This example performs a simple pre-execution check using device compliance, user clearance, and sensitivity label to decide whether Copilot access is allowed."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass\n",
        "\n",
        "@dataclass\n",
        "class RequestContext:\n",
        "    user_id: str\n",
        "    clearance: str\n",
        "    device_compliant: bool\n",
        "    sensitivity_label: str\n",
        "\n",
        "def allow_copilot(ctx: RequestContext) -> bool:\n",
        "    if not ctx.device_compliant:\n",
        "        return False\n",
        "    if ctx.clearance not in {\"Moderate\", \"High\"}:\n",
        "        return False\n",
        "    return ctx.sensitivity_label in {\"Public\", \"Internal\"}\n",
        "\n",
        "ctx = RequestContext(\"u123\", \"High\", True, \"Internal\")\n",
        "print({\"allowed\": allow_copilot(ctx)})\n",
        "\n",
        "test_contexts = [\n",
        "    RequestContext(\"u123\", \"High\", True, \"Internal\"),\n",
        "    RequestContext(\"u124\", \"Low\", True, \"Internal\"),\n",
        "    RequestContext(\"u125\", \"Moderate\", False, \"Public\"),\n",
        "    RequestContext(\"u126\", \"Moderate\", True, \"Secret\"),\n",
        "]\n",
        "\n",
        "rows = []\n",
        "for c in test_contexts:\n",
        "    rows.append({**asdict(c), \"allowed\": allow_copilot(c)})\n",
        "\n",
        "print(pd.DataFrame(rows))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Conditional access style session check\n",
        "\n",
        "The source material also included a PowerShell-style pre-check for a government tenant session. Here it is translated into Python to validate a session against device compliance, MFA completion, and trusted network requirements."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "session = {\n",
        "    \"UserPrincipalName\": \"analyst@agency.gov\",\n",
        "    \"DeviceCompliant\": True,\n",
        "    \"MFACompleted\": True,\n",
        "    \"NetworkZone\": \"Trusted\",\n",
        "}\n",
        "\n",
        "allowed = session[\"DeviceCompliant\"] and session[\"MFACompleted\"] and session[\"NetworkZone\"] == \"Trusted\"\n",
        "\n",
        "result = {\n",
        "    \"User\": session[\"UserPrincipalName\"],\n",
        "    \"Allowed\": allowed\n",
        "}\n",
        "\n",
        "print(result)\n",
        "\n",
        "sessions = [\n",
        "    session,\n",
        "    {\n",
        "        \"UserPrincipalName\": \"contractor@agency.gov\",\n",
        "        \"DeviceCompliant\": True,\n",
        "        \"MFACompleted\": False,\n",
        "        \"NetworkZone\": \"Trusted\",\n",
        "    },\n",
        "    {\n",
        "        \"UserPrincipalName\": \"remote@agency.gov\",\n",
        "        \"DeviceCompliant\": True,\n",
        "        \"MFACompleted\": True,\n",
        "        \"NetworkZone\": \"Untrusted\",\n",
        "    },\n",
        "]\n",
        "\n",
        "evaluated = []\n",
        "for s in sessions:\n",
        "    evaluated.append({\n",
        "        \"User\": s[\"UserPrincipalName\"],\n",
        "        \"Allowed\": s[\"DeviceCompliant\"] and s[\"MFACompleted\"] and s[\"NetworkZone\"] == \"Trusted\"\n",
        "    })\n",
        "\n",
        "print(pd.DataFrame(evaluated))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Retrieval filtering that preserves entitlements\n",
        "\n",
        "The blog stresses that prompt governance is not enough if retrieval can exceed user entitlements. This example filters documents by both ownership and maximum allowed label, showing how authorization must survive the retrieval step."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "documents = [\n",
        "    {\"id\": \"doc-1\", \"label\": \"Public\", \"owners\": {\"u123\", \"u999\"}},\n",
        "    {\"id\": \"doc-2\", \"label\": \"Secret\", \"owners\": {\"u999\"}},\n",
        "    {\"id\": \"doc-3\", \"label\": \"Internal\", \"owners\": {\"u123\"}},\n",
        "]\n",
        "\n",
        "def authorized_docs(user_id: str, max_label: str):\n",
        "    rank = {\"Public\": 1, \"Internal\": 2, \"Secret\": 3}\n",
        "    return [\n",
        "        d[\"id\"]\n",
        "        for d in documents\n",
        "        if user_id in d[\"owners\"] and rank[d[\"label\"]] <= rank[max_label]\n",
        "    ]\n",
        "\n",
        "print(authorized_docs(\"u123\", \"Internal\"))\n",
        "\n",
        "for user_id, max_label in [(\"u123\", \"Public\"), (\"u123\", \"Internal\"), (\"u999\", \"Secret\")]:\n",
        "    print({\"user_id\": user_id, \"max_label\": max_label, \"authorized\": authorized_docs(user_id, max_label)})"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Response filtering with simple DLP-style redaction\n",
        "\n",
        "The post highlights response filtering as part of the governed path from prompt to user response. This example applies lightweight regex-based redaction to generated text before delivery to simulate a DLP-style control."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import re\n",
        "\n",
        "def redact_sensitive(text: str) -> str:\n",
        "    text = re.sub(r\"\\b\\d{3}-\\d{2}-\\d{4}\\b\", \"[REDACTED-SSN]\", text)\n",
        "    text = re.sub(r\"\\b[A-Z]{2}\\d{6}\\b\", \"[REDACTED-ID]\", text)\n",
        "    return text\n",
        "\n",
        "draft = \"Employee SSN 123-45-6789 and badge AB123456 were referenced.\"\n",
        "print(redact_sensitive(draft))\n",
        "\n",
        "samples = [\n",
        "    \"Employee SSN 123-45-6789 and badge AB123456 were referenced.\",\n",
        "    \"No sensitive values here.\",\n",
        "    \"Backup identity XY654321 should be masked.\"\n",
        "]\n",
        "\n",
        "for s in samples:\n",
        "    print({\"original\": s, \"redacted\": redact_sensitive(s)})"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Minimal audit record as evidence\n",
        "\n",
        "The blog argues that auditors care about inventory, ownership, change history, and evidence more than prompts alone. This example creates a minimal audit record with timestamp, user, app, policy decision, boundary, and response action."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "audit = {\n",
        "    \"Timestamp\": datetime.now(timezone.utc).isoformat(),\n",
        "    \"User\": \"analyst@agency.gov\",\n",
        "    \"App\": \"Microsoft 365 Copilot\",\n",
        "    \"PromptHash\": \"sha256:9f2c...\",\n",
        "    \"PolicyDecision\": \"Allowed\",\n",
        "    \"DataBoundary\": \"USGov\",\n",
        "    \"ResponseAction\": \"DeliveredWithRedaction\"\n",
        "}\n",
        "\n",
        "print(json.dumps(audit, indent=2))\n",
        "\n",
        "audit_df = pd.DataFrame([audit])\n",
        "print(audit_df)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Retention-minded export for compliance review\n",
        "\n",
        "Evidence is more useful when it can be retained and reviewed consistently. This example mirrors the retention-oriented export pattern from the source material using Python objects and a simple filter on retention tags."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "records = [\n",
        "    {\"Id\": 1, \"Outcome\": \"Allowed\", \"RetentionTag\": \"7Years\"},\n",
        "    {\"Id\": 2, \"Outcome\": \"Blocked\", \"RetentionTag\": \"7Years\"},\n",
        "    {\"Id\": 3, \"Outcome\": \"Allowed\", \"RetentionTag\": \"30Days\"},\n",
        "]\n",
        "\n",
        "retained = [r for r in records if r[\"RetentionTag\"] == \"7Years\"]\n",
        "print(pd.DataFrame(retained))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Sequence validation of a governed AI request\n",
        "\n",
        "The original post included a sequence diagram showing policy evaluation before retrieval and inference, followed by audit logging. This cell simulates that sequence in Python so you can validate the order of operations and inspect the resulting evidence."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "def evaluate_policy(user_id: str, device_ok: bool, label: str) -> str:\n",
        "    if not device_ok:\n",
        "        return \"Deny:DeviceNonCompliant\"\n",
        "    if label not in {\"Public\", \"Internal\"}:\n",
        "        return \"Deny:LabelRestricted\"\n",
        "    return \"Allow\"\n",
        "\n",
        "def retrieve_context(user_id: str, max_label: str):\n",
        "    return authorized_docs(user_id, max_label)\n",
        "\n",
        "def generate_response(prompt: str, context_docs):\n",
        "    return f\"Draft response for '{prompt}' using {context_docs}\"\n",
        "\n",
        "def record_audit(user: str, decision: str, response_action: str):\n",
        "    return {\n",
        "        \"Timestamp\": datetime.now(timezone.utc).isoformat(),\n",
        "        \"User\": user,\n",
        "        \"PolicyDecision\": decision,\n",
        "        \"ResponseAction\": response_action\n",
        "    }\n",
        "\n",
        "user = \"u123\"\n",
        "prompt = \"Summarize my accessible HR documents\"\n",
        "decision = evaluate_policy(user, True, \"Internal\")\n",
        "\n",
        "if decision == \"Allow\":\n",
        "    context_docs = retrieve_context(user, \"Internal\")\n",
        "    draft = generate_response(prompt, context_docs)\n",
        "    final_response = redact_sensitive(draft)\n",
        "    audit_record = record_audit(user, decision, \"Delivered\")\n",
        "else:\n",
        "    context_docs = []\n",
        "    final_response = \"Request blocked by policy\"\n",
        "    audit_record = record_audit(user, decision, \"Blocked\")\n",
        "\n",
        "print({\n",
        "    \"decision\": decision,\n",
        "    \"context_docs\": context_docs,\n",
        "    \"response\": final_response,\n",
        "    \"audit\": audit_record\n",
        "})"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Buyer checklist as a validation worksheet\n",
        "\n",
        "The blog closes with a practical checklist for regulated buyers: written boundaries, admin-enforceable gates, geographic controls, a control-plane view, and restraint. This cell turns that checklist into a simple scoring worksheet to help rate current readiness from 1 to 5."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "checklist = [\n",
        "    \"Written deployment boundaries\",\n",
        "    \"Admin-enforceable gates\",\n",
        "    \"Geographic controls\",\n",
        "    \"Control-plane inventory and evidence\",\n",
        "    \"Restraint before approval\"\n",
        "]\n",
        "\n",
        "scores = {\n",
        "    \"Written deployment boundaries\": 4,\n",
        "    \"Admin-enforceable gates\": 3,\n",
        "    \"Geographic controls\": 2,\n",
        "    \"Control-plane inventory and evidence\": 3,\n",
        "    \"Restraint before approval\": 4\n",
        "}\n",
        "\n",
        "worksheet = pd.DataFrame([\n",
        "    {\"control\": item, \"score_1_to_5\": scores[item]} for item in checklist\n",
        "])\n",
        "\n",
        "print(worksheet)\n",
        "print({\"average_score\": round(worksheet[\"score_1_to_5\"].mean(), 2)})"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Next Steps\n",
        "\n",
        "This notebook validated the blog's main claim that enterprise-grade AI is less about feature count and more about enforceable boundaries, policy gates, and durable evidence. To extend this work, adapt the examples to your own tenant model, add richer role and connector logic, and map each control to your actual admin surfaces, logging systems, and compliance requirements."
      ]
    }
  ]
}