{
  "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": "The Bridge to Agent-Scale Git Infrastructure",
      "slug": "the-bridge-to-agent-scale-git-infrastructure",
      "generated_by": "LinkedIn Post Generator + Azure OpenAI",
      "generated_at": "2026-10-22T18:40:20.401Z"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# The Bridge to Agent-Scale Git Infrastructure\n",
        "\n",
        "This notebook turns the blog post into a hands-on validation workflow for agent-scale Git governance. It focuses on the core claim: Git is becoming a control plane for automated agents, so identity, provenance, quotas, and policy enforcement must happen before pull requests are created. The examples below simulate repository policy checks, contribution gateway decisions, audit metadata, and a lightweight inventory process for agent readiness."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "%pip install -q pandas requests"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass, asdict\n",
        "from typing import List, Dict, Any\n",
        "from datetime import datetime, timezone\n",
        "import json\n",
        "import os\n",
        "import re\n",
        "\n",
        "import pandas as pd\n",
        "import requests"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Problem framing: Git as an agent control plane\n",
        "\n",
        "The blog argues that code generation is not the hard part; governance at scale is. When agents can create thousands of commits and pull requests, the bottlenecks become identity, provenance, review capacity, quotas, and auditability.\n",
        "\n",
        "A useful way to validate that idea is to model the contribution flow explicitly: an agent proposes a change, a provenance envelope is built, policy checks run, quota and evidence checks are applied, and only then is a pull request allowed."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "flow_steps = [\n",
        "    \"Agent proposes change\",\n",
        "    \"Build provenance envelope\",\n",
        "    \"Policy validator\",\n",
        "    \"Risk tier checks\",\n",
        "    \"Quota + evidence checks\",\n",
        "    \"Open pull request\",\n",
        "    \"Branch policies + build validation\",\n",
        "    \"Human or delegated approval\",\n",
        "    \"Merge + audit trail\",\n",
        "]\n",
        "\n",
        "flow_df = pd.DataFrame({\n",
        "    \"step_number\": range(1, len(flow_steps) + 1),\n",
        "    \"step\": flow_steps,\n",
        "    \"purpose\": [\n",
        "        \"Start an automated contribution request\",\n",
        "        \"Capture identity, scope, evidence, and quota context\",\n",
        "        \"Centralize admission control\",\n",
        "        \"Reject unsafe changes early\",\n",
        "        \"Prevent abuse and missing evidence\",\n",
        "        \"Create PR only after validation\",\n",
        "        \"Apply downstream repository controls\",\n",
        "        \"Route to the right reviewer or delegated path\",\n",
        "        \"Preserve accountability and rollback context\",\n",
        "    ]\n",
        "})\n",
        "\n",
        "flow_df"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Define a repository risk policy and a sample provenance envelope\n",
        "\n",
        "This example models the minimum governance primitives described in the post. A repository policy defines risk tier, allowed paths, required evidence, and a daily quota, while the provenance envelope captures what the agent is trying to change and what evidence it provides."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass\n",
        "from typing import List, Dict\n",
        "\n",
        "@dataclass\n",
        "class RepoPolicy:\n",
        "    risk_tier: str\n",
        "    allowed_paths: List[str]\n",
        "    required_evidence: List[str]\n",
        "    daily_quota: int\n",
        "\n",
        "policy = RepoPolicy(\n",
        "    risk_tier=\"high\",\n",
        "    allowed_paths=[\"docs/\", \"infra/modules/\"],\n",
        "    required_evidence=[\"ticket\", \"test_report\", \"sbom\"],\n",
        "    daily_quota=3,\n",
        ")\n",
        "\n",
        "envelope: Dict[str, object] = {\n",
        "    \"agent_id\": \"agent-docs-17\",\n",
        "    \"repo\": \"platform/bridge\",\n",
        "    \"paths\": [\"docs/adr-021.md\", \"infra/modules/network/main.tf\"],\n",
        "    \"evidence\": {\n",
        "        \"ticket\": \"CHG-1042\",\n",
        "        \"test_report\": \"tests.xml\",\n",
        "        \"sbom\": \"sbom.spdx.json\"\n",
        "    },\n",
        "    \"requested_prs_today\": 1,\n",
        "}\n",
        "\n",
        "print(\"Policy:\")\n",
        "print(asdict(policy))\n",
        "print(\"\\nEnvelope:\")\n",
        "print(json.dumps(envelope, indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Validate the provenance envelope before a pull request exists\n",
        "\n",
        "This is the key architectural move in the post. Instead of letting an agent open a PR and relying on branch policies later, the envelope is validated up front against risk tier, path scope, evidence requirements, and quota limits."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass\n",
        "from typing import List, Dict\n",
        "\n",
        "@dataclass\n",
        "class RepoPolicy:\n",
        "    risk_tier: str\n",
        "    allowed_paths: List[str]\n",
        "    required_evidence: List[str]\n",
        "    daily_quota: int\n",
        "\n",
        "def validate_envelope(policy: RepoPolicy, envelope: Dict[str, object]) -> List[str]:\n",
        "    errors: List[str] = []\n",
        "    paths = envelope.get(\"paths\", [])\n",
        "    evidence = envelope.get(\"evidence\", {})\n",
        "    if policy.risk_tier == \"high\" and any(str(p).startswith(\"src/\") for p in paths):\n",
        "        errors.append(\"high-risk repositories cannot accept autonomous src/ changes\")\n",
        "    if any(not any(str(p).startswith(prefix) for prefix in policy.allowed_paths) for p in paths):\n",
        "        errors.append(\"one or more changed paths are outside the allowed automation scope\")\n",
        "    missing = [k for k in policy.required_evidence if k not in evidence]\n",
        "    if missing:\n",
        "        errors.append(f\"missing required evidence: {', '.join(missing)}\")\n",
        "    if int(envelope.get(\"requested_prs_today\", 0)) >= policy.daily_quota:\n",
        "        errors.append(\"daily pull request quota exceeded\")\n",
        "    return errors\n",
        "\n",
        "policy = RepoPolicy(\n",
        "    risk_tier=\"high\",\n",
        "    allowed_paths=[\"docs/\", \"infra/modules/\"],\n",
        "    required_evidence=[\"ticket\", \"test_report\", \"sbom\"],\n",
        "    daily_quota=3,\n",
        ")\n",
        "\n",
        "envelopes = [\n",
        "    {\n",
        "        \"name\": \"valid_change\",\n",
        "        \"agent_id\": \"agent-docs-17\",\n",
        "        \"repo\": \"platform/bridge\",\n",
        "        \"paths\": [\"docs/adr-021.md\"],\n",
        "        \"evidence\": {\"ticket\": \"CHG-1042\", \"test_report\": \"tests.xml\", \"sbom\": \"sbom.spdx.json\"},\n",
        "        \"requested_prs_today\": 1,\n",
        "    },\n",
        "    {\n",
        "        \"name\": \"bad_path\",\n",
        "        \"agent_id\": \"agent-docs-17\",\n",
        "        \"repo\": \"platform/bridge\",\n",
        "        \"paths\": [\"secrets/prod.env\"],\n",
        "        \"evidence\": {\"ticket\": \"CHG-1042\", \"test_report\": \"tests.xml\", \"sbom\": \"sbom.spdx.json\"},\n",
        "        \"requested_prs_today\": 1,\n",
        "    },\n",
        "    {\n",
        "        \"name\": \"missing_evidence\",\n",
        "        \"agent_id\": \"agent-docs-17\",\n",
        "        \"repo\": \"platform/bridge\",\n",
        "        \"paths\": [\"docs/adr-021.md\"],\n",
        "        \"evidence\": {\"ticket\": \"CHG-1042\"},\n",
        "        \"requested_prs_today\": 1,\n",
        "    },\n",
        "    {\n",
        "        \"name\": \"quota_exceeded\",\n",
        "        \"agent_id\": \"agent-docs-17\",\n",
        "        \"repo\": \"platform/bridge\",\n",
        "        \"paths\": [\"docs/adr-021.md\"],\n",
        "        \"evidence\": {\"ticket\": \"CHG-1042\", \"test_report\": \"tests.xml\", \"sbom\": \"sbom.spdx.json\"},\n",
        "        \"requested_prs_today\": 3,\n",
        "    },\n",
        "    {\n",
        "        \"name\": \"src_blocked_for_high_risk\",\n",
        "        \"agent_id\": \"agent-docs-17\",\n",
        "        \"repo\": \"platform/bridge\",\n",
        "        \"paths\": [\"src/app.py\"],\n",
        "        \"evidence\": {\"ticket\": \"CHG-1042\", \"test_report\": \"tests.xml\", \"sbom\": \"sbom.spdx.json\"},\n",
        "        \"requested_prs_today\": 1,\n",
        "    },\n",
        "]\n",
        "\n",
        "results = []\n",
        "for env in envelopes:\n",
        "    errs = validate_envelope(policy, env)\n",
        "    results.append({\n",
        "        \"scenario\": env[\"name\"],\n",
        "        \"approved\": len(errs) == 0,\n",
        "        \"errors\": \" | \".join(errs) if errs else \"\"\n",
        "    })\n",
        "\n",
        "pd.DataFrame(results)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Simulate policy tiers and routing by risk\n",
        "\n",
        "The post recommends moving review from a single PR queue to policy tiers. This example adds a simple risk classifier so low-risk changes can be routed differently from high-risk changes before reviewers spend time on them."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "def classify_risk(envelope: Dict[str, Any]) -> str:\n",
        "    paths = [str(p) for p in envelope.get(\"paths\", [])]\n",
        "    evidence = envelope.get(\"evidence\", {})\n",
        "    if any(p.startswith(\"infra/\") or p.startswith(\"deploy/\") or p.startswith(\"policy/\") for p in paths):\n",
        "        return \"high\"\n",
        "    if any(p.startswith(\"scripts/\") or p.startswith(\"config/\") for p in paths):\n",
        "        return \"medium\"\n",
        "    if all(p.startswith(\"docs/\") for p in paths) and {\"ticket\", \"test_report\"}.issubset(set(evidence.keys()) | {\"test_report\"}):\n",
        "        return \"low\"\n",
        "    return \"medium\"\n",
        "\n",
        "def route_review(risk_tier: str) -> str:\n",
        "    routes = {\n",
        "        \"low\": \"delegated-review-or-fast-lane\",\n",
        "        \"medium\": \"standard-owner-review\",\n",
        "        \"high\": \"named-owner-plus-strict-evidence\",\n",
        "    }\n",
        "    return routes.get(risk_tier, \"standard-owner-review\")\n",
        "\n",
        "sample_changes = [\n",
        "    {\"change\": \"docs fix\", \"paths\": [\"docs/runbook.md\"], \"evidence\": {\"ticket\": \"OPS-1\", \"test_report\": \"ok\"}},\n",
        "    {\"change\": \"script update\", \"paths\": [\"scripts/cleanup.py\"], \"evidence\": {\"ticket\": \"OPS-2\", \"test_report\": \"ok\"}},\n",
        "    {\"change\": \"infra module\", \"paths\": [\"infra/modules/network/main.tf\"], \"evidence\": {\"ticket\": \"OPS-3\", \"test_report\": \"ok\", \"sbom\": \"sbom.json\"}},\n",
        "]\n",
        "\n",
        "routing = []\n",
        "for item in sample_changes:\n",
        "    risk = classify_risk(item)\n",
        "    routing.append({\n",
        "        \"change\": item[\"change\"],\n",
        "        \"paths\": \", \".join(item[\"paths\"]),\n",
        "        \"risk\": risk,\n",
        "        \"review_route\": route_review(risk)\n",
        "    })\n",
        "\n",
        "pd.DataFrame(routing)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Gate pull request creation and emit an auditable decision record\n",
        "\n",
        "This example represents the contribution gateway described in the post. The gateway validates the request and emits a structured decision record that can be stored, queried, and attached to downstream workflows."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass\n",
        "from typing import List, Dict\n",
        "import json\n",
        "\n",
        "@dataclass\n",
        "class RepoPolicy:\n",
        "    risk_tier: str\n",
        "    allowed_paths: List[str]\n",
        "    required_evidence: List[str]\n",
        "    daily_quota: int\n",
        "\n",
        "def validate_envelope(policy: RepoPolicy, envelope: Dict[str, object]) -> List[str]:\n",
        "    missing = [k for k in policy.required_evidence if k not in envelope.get(\"evidence\", {})]\n",
        "    return missing\n",
        "\n",
        "policy = RepoPolicy(\"medium\", [\"docs/\", \"scripts/\"], [\"ticket\", \"test_report\"], 5)\n",
        "envelope = {\n",
        "    \"agent_id\": \"agent-42\",\n",
        "    \"paths\": [\"docs/runbook.md\"],\n",
        "    \"evidence\": {\"ticket\": \"OPS-88\", \"test_report\": \"ok\"}\n",
        "}\n",
        "errors = validate_envelope(policy, envelope)\n",
        "decision = {\n",
        "    \"agent_id\": envelope[\"agent_id\"],\n",
        "    \"approved\": not errors,\n",
        "    \"errors\": errors,\n",
        "    \"action\": \"open_pr\" if not errors else \"reject\"\n",
        "}\n",
        "print(json.dumps(decision, indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Simulate the contribution gateway sequence end to end\n",
        "\n",
        "The blog also shows a sequence where an agent submits an envelope, the validator checks tier, paths, evidence, and quota, and then either rejects the request or creates a PR with audit metadata. Here we model that sequence in Python and return a compact event log."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "def contribution_gateway(policy: RepoPolicy, envelope: Dict[str, Any]) -> Dict[str, Any]:\n",
        "    event_log = []\n",
        "    event_log.append({\"stage\": \"submit\", \"detail\": f\"Envelope submitted by {envelope.get('agent_id')}\"})\n",
        "\n",
        "    errors = validate_envelope(policy, envelope)\n",
        "    event_log.append({\"stage\": \"validate\", \"detail\": \"Checked tier, paths, evidence, quota\"})\n",
        "\n",
        "    if errors:\n",
        "        event_log.append({\"stage\": \"reject\", \"detail\": \"; \".join(errors)})\n",
        "        return {\n",
        "            \"approved\": False,\n",
        "            \"action\": \"reject\",\n",
        "            \"errors\": errors,\n",
        "            \"event_log\": event_log,\n",
        "        }\n",
        "\n",
        "    pr_payload = {\n",
        "        \"title\": envelope.get(\"title\", \"Agent change\"),\n",
        "        \"labels\": [\"agent-change\", f\"risk-{policy.risk_tier}\"],\n",
        "        \"artifactMetadata\": {\n",
        "            \"agent_id\": envelope.get(\"agent_id\"),\n",
        "            \"decision_time\": datetime.now(timezone.utc).isoformat(),\n",
        "        },\n",
        "    }\n",
        "    event_log.append({\"stage\": \"create_pr\", \"detail\": \"PR created with audit metadata\"})\n",
        "    event_log.append({\"stage\": \"branch_policy\", \"detail\": \"Build validation and reviewers triggered\"})\n",
        "\n",
        "    return {\n",
        "        \"approved\": True,\n",
        "        \"action\": \"open_pr\",\n",
        "        \"errors\": [],\n",
        "        \"pr_payload\": pr_payload,\n",
        "        \"event_log\": event_log,\n",
        "    }\n",
        "\n",
        "policy = RepoPolicy(\"medium\", [\"docs/\", \"scripts/\"], [\"ticket\", \"test_report\"], 5)\n",
        "request = {\n",
        "    \"agent_id\": \"agent-42\",\n",
        "    \"title\": \"Agent change: update runbook\",\n",
        "    \"paths\": [\"docs/runbook.md\"],\n",
        "    \"evidence\": {\"ticket\": \"OPS-88\", \"test_report\": \"ok\"},\n",
        "}\n",
        "\n",
        "result = contribution_gateway(policy, request)\n",
        "print(json.dumps(result, indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Attach audit metadata to a pull request payload\n",
        "\n",
        "Consistency matters for governance. If every agent uses a different PR shape, labels, and metadata structure, downstream policy engines become fragile. This example standardizes the payload the gateway would send onward."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import json\n",
        "from datetime import datetime, timezone\n",
        "\n",
        "payload = {\n",
        "    \"sourceRefName\": \"refs/heads/agents/agent-42-doc-fix\",\n",
        "    \"targetRefName\": \"refs/heads/main\",\n",
        "    \"title\": \"Agent change: update runbook\",\n",
        "    \"description\": \"Automated change with validated provenance.\",\n",
        "    \"labels\": [\"agent-change\", \"provenance-validated\", \"risk-medium\"],\n",
        "    \"artifactMetadata\": {\n",
        "        \"agent_id\": \"agent-42\",\n",
        "        \"decision_time\": datetime.now(timezone.utc).isoformat(),\n",
        "        \"evidence\": [\"ticket:OPS-88\", \"test_report:ok\"],\n",
        "    },\n",
        "}\n",
        "\n",
        "print(json.dumps(payload, indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Required variables for live Azure DevOps inventory\n",
        "\n",
        "If you want to run the next examples against a real Azure DevOps environment, set these environment variables first:\n",
        "\n",
        "- `AZDO_ORG_URL` — for example `https://dev.azure.com/contoso`\n",
        "- `AZDO_PROJECT` — project name\n",
        "- `AZDO_PAT` — personal access token with read access to repositories and policies\n",
        "\n",
        "The notebook keeps the code in Python and uses the Azure DevOps REST API instead of PowerShell so it can run directly here."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Authenticate to Azure DevOps and list repositories in a project\n",
        "\n",
        "The blog recommends starting implementation by inventorying the current state: bot accounts, policy exceptions, unrestricted automation rights, and weakly protected repositories. A practical first step is to enumerate repositories and their default branches."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "def azdo_headers_from_pat(pat: str) -> Dict[str, str]:\n",
        "    import base64\n",
        "    token = base64.b64encode(f\":{pat}\".encode(\"ascii\")).decode(\"ascii\")\n",
        "    return {\"Authorization\": f\"Basic {token}\"}\n",
        "\n",
        "def list_repositories(org_url: str, project: str, pat: str) -> pd.DataFrame:\n",
        "    url = f\"{org_url}/{project}/_apis/git/repositories?api-version=7.1-preview.1\"\n",
        "    response = requests.get(url, headers=azdo_headers_from_pat(pat), timeout=30)\n",
        "    response.raise_for_status()\n",
        "    repos = response.json().get(\"value\", [])\n",
        "    return pd.DataFrame([\n",
        "        {\n",
        "            \"name\": r.get(\"name\"),\n",
        "            \"id\": r.get(\"id\"),\n",
        "            \"defaultBranch\": r.get(\"defaultBranch\")\n",
        "        }\n",
        "        for r in repos\n",
        "    ])\n",
        "\n",
        "org_url = os.getenv(\"AZDO_ORG_URL\")\n",
        "project = os.getenv(\"AZDO_PROJECT\")\n",
        "pat = os.getenv(\"AZDO_PAT\")\n",
        "\n",
        "if org_url and project and pat:\n",
        "    repo_df = list_repositories(org_url, project, pat)\n",
        "else:\n",
        "    repo_df = pd.DataFrame([\n",
        "        {\"name\": \"platform-bridge\", \"id\": \"repo-001\", \"defaultBranch\": \"refs/heads/main\"},\n",
        "        {\"name\": \"infra-core\", \"id\": \"repo-002\", \"defaultBranch\": \"refs/heads/main\"},\n",
        "        {\"name\": \"docs-site\", \"id\": \"repo-003\", \"defaultBranch\": \"refs/heads/main\"},\n",
        "    ])\n",
        "\n",
        "repo_df"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Enumerate branch policies to find build validations and protected branches\n",
        "\n",
        "The next inventory step is the policy layer. The goal is not perfection on day one; it is to find obvious gaps such as critical repositories without build validation, weak default branch protection, or inconsistent policy coverage across projects."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "def list_branch_policies(org_url: str, project: str, pat: str) -> pd.DataFrame:\n",
        "    url = f\"{org_url}/{project}/_apis/policy/configurations?api-version=7.1-preview.1\"\n",
        "    response = requests.get(url, headers=azdo_headers_from_pat(pat), timeout=30)\n",
        "    response.raise_for_status()\n",
        "    policies = response.json().get(\"value\", [])\n",
        "\n",
        "    rows = []\n",
        "    for p in policies:\n",
        "        scope = (p.get(\"settings\") or {}).get(\"scope\") or [{}]\n",
        "        first_scope = scope[0] if scope else {}\n",
        "        display_name = ((p.get(\"type\") or {}).get(\"displayName\"))\n",
        "        if p.get(\"isEnabled\") and re.search(r\"Build|Minimum number of reviewers\", str(display_name)):\n",
        "            rows.append({\n",
        "                \"Policy\": display_name,\n",
        "                \"Branch\": first_scope.get(\"refName\"),\n",
        "                \"RepositoryId\": first_scope.get(\"repositoryId\"),\n",
        "                \"isBlocking\": p.get(\"isBlocking\"),\n",
        "            })\n",
        "    return pd.DataFrame(rows)\n",
        "\n",
        "if org_url and project and pat:\n",
        "    policy_df = list_branch_policies(org_url, project, pat)\n",
        "else:\n",
        "    policy_df = pd.DataFrame([\n",
        "        {\"Policy\": \"Build\", \"Branch\": \"refs/heads/main\", \"RepositoryId\": \"repo-001\", \"isBlocking\": True},\n",
        "        {\"Policy\": \"Minimum number of reviewers\", \"Branch\": \"refs/heads/main\", \"RepositoryId\": \"repo-001\", \"isBlocking\": True},\n",
        "        {\"Policy\": \"Build\", \"Branch\": \"refs/heads/main\", \"RepositoryId\": \"repo-002\", \"isBlocking\": True},\n",
        "        {\"Policy\": \"Minimum number of reviewers\", \"Branch\": \"refs/heads/main\", \"RepositoryId\": \"repo-003\", \"isBlocking\": False},\n",
        "    ])\n",
        "\n",
        "policy_df"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Flag repositories that need an agent-readiness review\n",
        "\n",
        "This lightweight pass separates repositories that are reasonable pilot candidates from those that need deeper review. Repositories tied to infrastructure, platform, or production should automatically receive stricter scrutiny."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "def flag_agent_readiness(repos: pd.DataFrame, policies: pd.DataFrame) -> pd.DataFrame:\n",
        "    rows = []\n",
        "    for _, repo in repos.iterrows():\n",
        "        repo_policies = policies[policies[\"RepositoryId\"] == repo[\"id\"]] if not policies.empty else pd.DataFrame()\n",
        "        has_build = False if repo_policies.empty else (repo_policies[\"Policy\"] == \"Build\").any()\n",
        "        protected = False if repo_policies.empty else repo_policies[\"isBlocking\"].fillna(False).any()\n",
        "        name = str(repo[\"name\"])\n",
        "        rows.append({\n",
        "            \"Repository\": name,\n",
        "            \"DefaultBranch\": repo[\"defaultBranch\"],\n",
        "            \"HasBuildValidation\": bool(has_build),\n",
        "            \"ProtectedBranch\": bool(protected),\n",
        "            \"AutomationAccountReview\": \"Required\" if re.search(r\"infra|platform|prod\", name, re.IGNORECASE) else \"Recommended\"\n",
        "        })\n",
        "    return pd.DataFrame(rows)\n",
        "\n",
        "review_df = flag_agent_readiness(repo_df, policy_df)\n",
        "review_df"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Measure governance quality for a constrained pilot\n",
        "\n",
        "The post recommends measuring governance quality, not just code volume. This example creates a small synthetic dataset and calculates the metrics suggested in the implementation plan: rejection rate, reviewer latency, override rate, post-merge reversion rate, CI cost per accepted change, and failure rate by risk tier."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "pilot_data = pd.DataFrame([\n",
        "    {\"change_id\": 1, \"risk_tier\": \"low\", \"approved\": True,  \"reviewer_latency_hours\": 1.2, \"override\": False, \"reverted\": False, \"ci_cost\": 2.5, \"failed\": False},\n",
        "    {\"change_id\": 2, \"risk_tier\": \"low\", \"approved\": False, \"reviewer_latency_hours\": 0.2, \"override\": False, \"reverted\": False, \"ci_cost\": 0.5, \"failed\": True},\n",
        "    {\"change_id\": 3, \"risk_tier\": \"medium\", \"approved\": True,  \"reviewer_latency_hours\": 3.4, \"override\": True,  \"reverted\": False, \"ci_cost\": 6.0, \"failed\": False},\n",
        "    {\"change_id\": 4, \"risk_tier\": \"high\", \"approved\": False, \"reviewer_latency_hours\": 0.5, \"override\": False, \"reverted\": False, \"ci_cost\": 1.0, \"failed\": True},\n",
        "    {\"change_id\": 5, \"risk_tier\": \"high\", \"approved\": True,  \"reviewer_latency_hours\": 6.8, \"override\": False, \"reverted\": True,  \"ci_cost\": 12.0, \"failed\": False},\n",
        "    {\"change_id\": 6, \"risk_tier\": \"medium\", \"approved\": True,  \"reviewer_latency_hours\": 2.1, \"override\": False, \"reverted\": False, \"ci_cost\": 5.5, \"failed\": False},\n",
        "])\n",
        "\n",
        "rejection_rate = 1 - pilot_data[\"approved\"].mean()\n",
        "reviewer_latency = pilot_data[\"reviewer_latency_hours\"].mean()\n",
        "override_rate = pilot_data[\"override\"].mean()\n",
        "post_merge_reversion_rate = pilot_data.loc[pilot_data[\"approved\"], \"reverted\"].mean()\n",
        "ci_cost_per_accepted_change = pilot_data.loc[pilot_data[\"approved\"], \"ci_cost\"].mean()\n",
        "failure_by_risk = pilot_data.groupby(\"risk_tier\")[\"failed\"].mean().reset_index(name=\"failure_rate\")\n",
        "\n",
        "summary_metrics = pd.DataFrame([\n",
        "    {\"metric\": \"rejection_rate\", \"value\": rejection_rate},\n",
        "    {\"metric\": \"reviewer_latency_hours_avg\", \"value\": reviewer_latency},\n",
        "    {\"metric\": \"override_rate\", \"value\": override_rate},\n",
        "    {\"metric\": \"post_merge_reversion_rate\", \"value\": post_merge_reversion_rate},\n",
        "    {\"metric\": \"ci_cost_per_accepted_change\", \"value\": ci_cost_per_accepted_change},\n",
        "])\n",
        "\n",
        "print(\"Summary metrics\")\n",
        "display(summary_metrics)\n",
        "print(\"\\nFailure rate by risk tier\")\n",
        "display(failure_by_risk)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Validate identity segmentation and quota controls\n",
        "\n",
        "A major theme in the post is that agents need workload identities, not shared bot credentials, and that quotas must be enforced before scale. This example checks a small identity inventory for common anti-patterns and simulates quota enforcement."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "identity_inventory = pd.DataFrame([\n",
        "    {\"agent_role\": \"docs-agent\", \"identity\": \"mi-docs-dev\", \"environment\": \"dev\", \"repo_scope\": \"docs-site\", \"shared_credential\": False},\n",
        "    {\"agent_role\": \"infra-agent\", \"identity\": \"shared-bot\", \"environment\": \"prod\", \"repo_scope\": \"infra-core\", \"shared_credential\": True},\n",
        "    {\"agent_role\": \"rollback-agent\", \"identity\": \"mi-rollback-prod\", \"environment\": \"prod\", \"repo_scope\": \"platform-bridge\", \"shared_credential\": False},\n",
        "])\n",
        "\n",
        "identity_inventory[\"identity_issue\"] = identity_inventory.apply(\n",
        "    lambda r: \"shared credential not allowed\" if r[\"shared_credential\"] else \"ok\", axis=1\n",
        ")\n",
        "\n",
        "quota_state = {\n",
        "    \"agent-42\": {\"daily_quota\": 5, \"requested_today\": 4},\n",
        "    \"agent-docs-17\": {\"daily_quota\": 3, \"requested_today\": 3},\n",
        "}\n",
        "\n",
        "quota_results = []\n",
        "for agent_id, state in quota_state.items():\n",
        "    quota_results.append({\n",
        "        \"agent_id\": agent_id,\n",
        "        \"daily_quota\": state[\"daily_quota\"],\n",
        "        \"requested_today\": state[\"requested_today\"],\n",
        "        \"can_open_next_pr\": state[\"requested_today\"] < state[\"daily_quota\"]\n",
        "    })\n",
        "\n",
        "print(\"Identity segmentation check\")\n",
        "display(identity_inventory)\n",
        "print(\"\\nQuota enforcement check\")\n",
        "display(pd.DataFrame(quota_results))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Summary\n",
        "\n",
        "This notebook validated the blog's central architecture in executable form: agent-originated changes should carry a provenance envelope, be checked against policy tiers and quotas before PR creation, and pass through a platform-owned contribution gateway that emits auditable decisions. It also translated the implementation plan into practical inventory and readiness checks for repositories, policies, identities, and pilot metrics.\n",
        "\n",
        "## Next Steps\n",
        "\n",
        "1. Replace the sample data with live Azure DevOps inventory using `AZDO_ORG_URL`, `AZDO_PROJECT`, and `AZDO_PAT`.\n",
        "2. Expand the provenance envelope schema to include initiating principal, workflow ID, rollback path, and validation artifacts.\n",
        "3. Add path-based policy rules for production configuration, IaC, secrets, and deployment manifests.\n",
        "4. Persist gateway decision records to a database or log platform for audit and reporting.\n",
        "5. Pilot the model in one low-risk repository before extending it to infrastructure and production control surfaces."
      ]
    }
  ]
}