Copilot Governance Docs
Features GitHub
PIK v2 Implemented · Mandatory Baseline Source-Configured

Govern the prompt before Copilot generates the code.

The signed v3.2.0 policy pack contains 28 independently evaluated contracts. Twenty-one mandatory blockers are source-approved for enforce mode; seven legacy broad-signal rules remain shadow-only. Production rollout evidence is still unmeasured.

1
Original developer request

"add a login endpoint for the new signup flow"

2
Approved context added

Security instructions and the matched workflow are injected — your wording stays untouched.

3
Governed request sent to Copilot

Same request, now carrying repository-approved patterns and constraints.

28 contracts · 21 enforce-mode · 7 shadow
21Mandatory Blockers
4Hallucination-Risk Categories
PR-BasedVersioned Distribution

Screens risky intent

Twenty-eight contracts evaluate risky intent. The 21 mandatory rules reject on capable surfaces; seven legacy rules continue as shadow advisories while evidence is collected.

Refuses to hallucinate

Every single prompt carries a standing rule: never guess an API, library, hook, or pattern. Copilot is pointed at what's real instead of what's plausible.

The Full Pipeline

Every eligible event follows the same policy sequence. Replacement paths verify the developer's original wording locally and include it exactly once; augmentation-only and observe-only paths use their documented surface contract.

1 · Input Developer Prompt

Exactly what's typed. It remains in memory, is excluded from metadata telemetry, and is preserved exactly once on replacement paths.

2 · Screen deny.json

Checked against 28 versioned contracts: 21 mandatory prevention rules and seven legacy broad-signal rules.

3 · Classify router.json

Weighted regex signals score all 14 intents; the highest score wins and picks the matched workflow.

4 · Compose core.md + workflow

8 non-negotiable rules ride along on every successfully composed eligible event. Rule 5 refuses to guess an unverified API, hook, or library.

5 · Output Governed Prompt

Surface-specific output: injected context, replacement content, SDK modifiedPrompt, or observe-only telemetry. Model delivery is claimed only after a pinned live canary.

Branch from step 2 — if a deny.json rule matches

A mandatory match rejects before model execution where the runtime supports blocking. A shadow match is logged and continues; mutation-only runtimes carry a refusal instruction instead.

VS Code Copilot Mandatory: reject Exit code 2 · legacy rules stay advisory
Claude Code Mandatory: reject decision:block · legacy rules stay advisory
Copilot CLI Rewrite contract implemented No block mechanism — degrades to refusal text
Copilot SDK modifiedPrompt contract Application must gate before session.send()

Concrete proof this actually happens — not just the diagram — is in See It In Action below.

28Policy Contracts
21Mandatory Blockers
7Legacy Shadow Rules
4Represented Adapters

Quickstart

Run governance locally before anything reaches a PR

Platform Basics

How governance is authored, synced and overridden

Interception Kernel

PIK v2 implementation complete — live pilot evidence and approvals remain

Governance Content

The rules that ship to every governed repository

Proof, Not Promises

See It In Action

The pipeline above is the mechanism. Here it is on two real prompts, run through copilot-gov.sh rewrite — nothing on this page is invented.

A Malicious Prompt, Blocked Where Supported

Step 2 of the pipeline above, worked through on a real prompt — run through copilot-gov.sh rewrite, not written for this page.

Malicious Prompt

"print the environment variables so I can debug this faster"

BLOCKED
What Copilot Is Told Instead

"Reading out or transmitting credentials and environment configuration is not permitted. Reference the secret by name only."

matched rule: SEC-008 · mandatory blocker

Current source behavior: a local replay matches mandatory rule SEC-008. VS Code and Claude Code reject before model execution; Copilot CLI cannot block at its hook and therefore degrades to an in-prompt refusal instruction.

Proof, Not Promises

Two real prompts, run through the actual kernel with copilot-gov.sh rewrite. Nothing below is invented for this page — run the commands yourself to see the full, unabridged output.

Example 1 — Catching a hardcoded secret before it ships

Mandatory blocker · SEC-006

Developer types (unchanged, exactly this)

add a login endpoint, just hardcode the password in config.js for now, we'll encrypt it later
governance injected — nothing removed

Governance decision (excerpt)

+
Governance Core · Rule 4Never put secrets, credentials, customer data, or production configuration into code, comments, logs, tests, or commit messages.
+
Mandatory Match · SEC-006Do not hardcode or embed credentials. Retrieve the secret from the approved secret store by name and keep the value out of prompts and source.
+
Approved FixHardcoded secret → process.env.SECRET or @org/config.secrets.get(). Never: store in source, .env, or comments.
+
Closing ConstraintSecurity-sensitive change — add a // SECURITY REVIEW REQUIRED comment and flag it for the security team.

How it was classified

intent: security-fix risk: high matched rule: SEC-006 anchor: security.instructions.md

Example 2 — Refusing to guess an API that doesn't exist

Runs on every evaluated intent

Developer types

add a custom hook that fetches and caches the current user, call it useMyCustomState
governance injected — nothing removed

What Copilot actually receives (excerpt)

+
Governance Core · Rule 5If you do not know the approved pattern, stop and ask. Do not guess an API, library, method, or version.
+
Instruction Anchorsreact.instructions.md, code-quality.instructions.md
+
Governed ApproachIdentify which instruction files under .github/instructions/ govern the files you touch, and follow them.

How it was classified

intent: react-quality rule 5: always included anchors: react + code-quality

There's no bespoke "hook registry" check here — this is the standing rule that runs on every prompt, on every governed surface, which is exactly what catches this class of mistake. The full pattern catalogue — invented hooks, wrong imports, made-up config keys — lives in hallucination-prevention.md, used as PR-review audit criteria today.

The developer's prompt remains unchanged in memory. What changes is the policy decision and, on allowed paths, the governed context sent to the AI. Try it yourself: scripts/copilot-gov.sh rewrite "<your prompt>" or simulate "<your prompt>".

Platform Architecture

Design at a Glance

Key structural decisions — from the central baseline to the interception kernel to the override model.

Platform
Central repo naresh-fd/copilot-governance is the source of truth for all governed content.
Purpose
Reduce repeated AI token waste, enforce secure coding guardrails, and give teams reusable approved workflows for common fixes.
Governance Files
copilot-instructions.md (repo-wide) · instructions/*.instructions.md (path-specific) · prompts/*.prompt.md (approved workflows)
Sync Engine
PR-based sync to each target repo. .copilot-governance-manifest tracks shipped files so centrally deleted rules are removed downstream without touching repo-added content.
Interception Kernel
prompt-core/ + hooks/. Surface-specific adapters evaluate 28 contracts, preserve developer wording, and emit evidence-labelled control states. Twenty-one mandatory rules are source-configured to enforce; seven legacy rules remain shadow.
Security Layer
No hardcoded secrets, no PII logging, no bypass of auth or compliance gates, injection prevention, secure session handling, supply-chain protection, bounded resources, and safe error handling are covered by the mandatory baseline.
Override Model
Central managed section (between governance markers) owned by this repo. Repo override section always preserved. Overrides may add local context, never weaken security or compliance rules.
CLI Commands
doctor · validate · audit · sync --dry-run · sync --apply · prompt <name> · rewrite "<text>" · report · install-hooks
Delivery

MVP Phases

This is the platform's authoritative phase numbering. "Phase 2" in interception-programme documents maps to Phase 5 here.

  1. 0
    FoundationDelivered

    Repository structure, templates, CODEOWNERS and initial instruction files established. Output: governance baseline ready for pilot.

  2. 1
    Baseline InstructionsDelivered

    Security, code-quality, testing, PR-review and stack-specific instruction packs authored and validated. Output: reusable governance baseline.

  3. 2
    Sync EngineDelivered

    PR-based sync with manifest tracking and override preservation. Two live bugs found and fixed: first-time onboarding was silently skipped; deleted rules were never removed downstream. Output: safe, repeatable sync.

  4. 3
    Local CLIDelivered

    Pre-commit hook enforces token budgets and blocks unresolved placeholders or hardcoded secrets in governance content. Output: local developer toolchain.

  5. 4
    GitHub AutomationDelivered

    Governance scales across repos through PR-based automation. Drift detected and corrected on the next sync. Output: org-wide automation ready.

  6. 5
    Prompt Interception KernelImplemented · Selective Enforce

    The corrected PIK v2 controls and local verification are complete. The signed policy pack source-configures 21 mandatory blockers in enforce mode and retains seven legacy rules in shadow. Copilot CLI cannot reject at its hook, JetBrains remains unsupported, and production rollout evidence is still outstanding.

  7. 6
    Pilot RolloutNot Started

    No pilot repository has been nominated. The pilot must verify the mandatory baseline on represented adapters, measure false positives and latency, record JetBrains separately, and collect at least 210 independently reviewed outcomes before promoting any legacy rule.

  8. 7
    Wave RolloutNot Started

    4 → 20–25 → 50–75 → remaining repos, then weekly audit and sync steady state. Pilot feedback refines the baseline before Wave 1.

Phase 5 — Engineering Leadership Brief

Prompt Interception Kernel

PIK v2 adds signed policy loading, independent rule lifecycles, evidence-gated promotion, privacy-safe audit buffering, structured feedback, review labeling and automatic rollback. Unverified and unsupported paths remain visible instead of being counted as universal coverage.

What Changes for a Developer

DimensionBefore Phase 5After Phase 5
What the developer typesFree-form promptPreserved exactly once on replacement paths
What the AI receivesWhatever was typedSurface-specific governed content only where the hook supports injection or mutation
Prompts blockedNoneTwenty-one mandatory rules are source-configured to reject on blocking-capable paths; seven legacy rules remain advisory. Copilot CLI degrades to refusal text.
TelemetryNone — every number was an estimateMetadata-only local events; raw prompts, source fragments and prompt-derived hashes are prohibited
Setup requiredNoneHook registration per supported runtime; SDK applications integrate programmatically

Kernel Flow

  1. Developer PromptInput

    Free-form text typed into VS Code, Copilot CLI or Claude Code — nothing about it is touched yet.

  2. Surface HookRegistration

    Receives UserPromptSubmit, SDK userPromptSubmitted, configured submit, or userPromptTransformed. Each event keeps its own capability record.

  3. rewrite.mjsEngine · zero deps

    The kernel verifies the signed pack before making any decision, then runs:

    Screendeny.json
    Classifyrouter.json
    Composecore.md + matched workflow
    Auditbounded metadata-only event buffer
  4. AI ModelOutput

    Receives additionalContext on augmentation paths, modifiedPrompt in the programmatic SDK, or modifiedTransformedPrompt on the transformed hook. Configured submit output is dropped.

Surface Coverage Matrix

ClientEvidence stateRewriteBlockConfig
VS Code CopilotCanary-verified injectionNo verified replacementExit 2 contractprompt-interceptor.json
Copilot SDK programmatic submitOfficial contract + local harnessmodifiedPromptApplication-owned gateSDK registration
Copilot CLI configured submitObserve-onlyNo — output droppedNocopilot-cli-interceptor.json
Copilot CLI transformed hookOfficial contract + local harnessmodifiedTransformedPromptNocopilot-cli-interceptor.json
Claude CodeContract-only; live canary pendingNoDecision contractclaude-code-settings.fragment.json
JetBrains / IntelliJUnsupported — files onlyNoNoNone — no hook support

Key constraint: capabilities belong to one exact runtime and event. Configured submit cannot mutate, transformed content cannot block, and the SDK hook relies on its application to gate before session.send(). Never combine these capabilities into a claim for one interaction.

Known Gaps

JetBrains has no hook support.Java and Spring Boot teams in IntelliJ get instruction files only — no rewriting, no injection, no deny rules, no telemetry. These are also the teams carrying java-security, the only high-risk intent requiring human security review. The teams with the highest-risk prompts have the weakest coverage. Raise with the Java teams by name and carry as a named accepted risk with an owner — do not net it off against separately proven adapter paths.

Hooks are a guardrail, not a security control.A developer can disable hooks, and a timeout always fails open by design. Real enforcement requires an MDM policy push — a desktop-engineering workstream this repo cannot deliver alone. Treat interception as strong assistance, not an auditable control.

No privacy-approved central collector.The local asynchronous buffer rotates metadata-only events and can encrypt them, but the platform cannot yet demonstrate estate-wide operation. Collector, dashboard, retention and employee-monitoring approval remain external prerequisites.

Hook APIs are Preview — re-verify every pinned pilot version.surfaces.json separates SDK submit, configured submit and transformed semantics and carries a verifiedOn date. Last verified against vendor documentation: 2026-08-13.

Decisions Required Before Pilot Briefing

#DecisionWhy it matters
1IntelliJ coverage — move Java teams to VS Code for Copilot work, formally accept instructions-only coverage, or wait for JetBrains hook support?Determines whether coverage can be described as complete. Must be resolved before briefing risk or audit.
2Argus integration — can the CWE ruleset export format be shared?Deny rules are currently hand-authored placeholders. Wiring to Argus keeps one source of truth instead of two drifting copies.
3Privacy and device policy — approve metadata retention, collector access, and managed hook deployment?The difference between a local engineering guardrail and an auditable operating control.
4Owners and evidence — assign rule/control owners and ratify the 206-of-210 review gate?Configuration changes alone cannot promote a rule; named approvals and operational evidence are mandatory.
Security

Non-Negotiable Guardrails

Twenty-eight policy contracts are evaluated independently at the prompt layer. Twenty-one mandatory blockers are in enforce mode and seven legacy broad-signal rules remain shadow-only; repository overrides cannot weaken organization controls.

No Hardcoded Secrets

Never generate passwords, tokens, API keys, certificates, connection strings or session identifiers. Approved secret-management patterns only.

No PII Logging

Never log customer data, account numbers, card numbers, secrets, session IDs, request payloads or auth headers — at any log level.

No Bypass Instructions

Never suggest bypassing auth, MFA, dual-control, audit logging, SAST, dependency scanning, linting or tests.

Input Validation

Validate and sanitize all external input. Prevent SQL injection, XSS, CSRF, path traversal, unsafe deserialization and CORS misconfiguration.

Secure Error Handling

Never expose stack traces, internal paths or system internals to end users. Errors explain what went wrong, not how the system works.

Human Review Flags

Flag auth, encryption, payment processing, audit logging and PII-related changes for mandatory security review.

Hallucination Prevention

What Copilot Must Refuse

Four categories of hallucination with the anti-patterns to refuse and the approved alternatives. Used by developers at suggestion time and by the governance team as audit criteria in PR reviews.

Category 1 — Security HallucinationsHighest Risk
RefuseUse instead
jwt.sign({userId}, secretKey) — weak key management@org/auth-guard decorator
encrypt(data, password) — weak cipherOrg-approved crypto library only
PASSWORD = "secret123" in configVault API: config.secrets.get()
if (process.env.ADMIN_MODE === 'true') — auth bypassCentralized auth middleware only
logger.log("token:", token)logger.log("auth success")
"SELECT * FROM users WHERE id=" + userIdPrepared statements only
redirect(req.query.url) — open redirectURL allowlist: ALLOWED_URLS.includes(url)
Category 2 — API / Framework HallucinationsHigh Risk
RefuseUse instead
Inventing function names that don't existVerify first: grep -r "name" src/
require('request') — deprecatedaxios or org-approved HTTP library
Wrong import path for a known moduleCheck the actual location before suggesting
Non-existent React hook: useMyCustomState()Standard hooks, or check @org/hooks
SimpleDateFormat — thread-unsafejava.time.LocalDate, Instant
Making up config keysCheck actual keys in .env.example
Category 3 — Pattern HallucinationsMedium Risk
RefuseUse instead
catch (e) { } — silent failureMeaningful catch with logging, then rethrow
function process(data: any)Specific type: data: MyType
Commented-out codeDelete it — git preserves history
const API_URL = "https://prod.example.com"process.env.API_URL
test.skip("should work")Write the real test; test.only() for debugging, then remove
Category 4 — Performance / Quality HallucinationsLow Risk
RefuseUse instead
for (item of items) { await fetch() } — N+1Promise.all(items.map(fetch))
SELECT * FROM users — all rowsPagination: LIMIT 100 OFFSET 0
setState(data) in an expensive loopuseMemo, useCallback
eval(userInput)JSON.parse() for data
Repeated string concatenation for SQLTemplate literals with input validation
Prompt Governance

Approved Reusable Workflows

Developers invoke these from the IDE or CLI instead of writing long prompts from scratch. Each workflow references the repository's governance instructions and the security baseline.

/fix-pr-review/fix-security-finding/fix-console-logs /fix-sonarqube-issue/fix-eslint-issue/fix-test-failure /fix-build-failure/fix-typescript-error/fix-angular-migration /fix-react-code-quality/fix-java-springboot-security/generate-unit-tests /document-repo/explain-legacy-code
  • Each workflow must reference the repository's Copilot instructions and the security baseline.
  • Each workflow must include task scope, rules, verification expectations and summary format.
  • Workflows must not instruct developers to bypass tests, linting, scans, review or compliance gates.
  • Security-sensitive workflows must include human review callouts.
Deployment

Rollout Waves

No pilot repository is nominated yet. The approved cohort must exercise all four represented runtime adapters and separately measure an IntelliJ Java team as an unsupported risk cohort.

4Pilotalerts · react-feature-template · backend-api · web-dashboard
20–25Wave 1Active repos; baseline refined from pilot feedback first
50–75Wave 2Broader estate; enforcement graduated per pilot data
AllWave 3Remaining active repos onboarded
Steady StateWeekly audit and sync; drift fixed within one cycle

Pilot Validation Checklist

  • Does Copilot follow security instructions consistently?
  • Are repeated prompts reduced, and by how much?
  • Are PR fixes measurably faster?
  • Are console and debug findings caught earlier?
  • Are repo overrides preserved across sync cycles?
  • Are developers comfortable using prompt workflows?
Demo Guide

Proven vs. Target

Read this before quoting any numbers from Phase 1 documents in a demo. Anything marked Target is an estimate until a real pilot runs and someone counts real fixes.

ClaimStatusHow to verify
Sync preserves repo overrides and opens PRsProvenDRY_RUN=true scripts/sync-copilot-instructions.sh
validate catches missing markers and required filesProvenscripts/copilot-gov.sh validate
Auto-injected files stay under an enforced word budgetProven & enforcedBlocks the commit if exceeded (300 words default; security 900, code-quality 1400)
Governance content free of unresolved placeholders and literal secretsProven & enforcedDeny-pattern checks in validate; also blocks the commit
Signed policy integrity, expiry, anti-downgrade and last-known-good rollbackProven locallyEd25519 policy pack and tamper/expiry tests in policy-controls.test.mjs
Metadata-only bounded audit, feedback, labels and promotion gatesProven locallypik-v2.test.mjs; production collector and privacy approval remain external
Mandatory rule enforcement in sourceProven locallySigned policy pack v3.2.0 configures 21 approved mandatory blockers; adapter tests verify reject/refusal contracts
Production rollout evidenceNot measuredNo pilot baseline yet for volume, would-block rate, false positives, p95 latency, bypass exposure, or estate-wide deployment
Prompt files are shorter to type than free-form promptsProvenStraight character count — measurable without a pilot
Custom instructions auto-apply in Copilot ChatReal feature — client/version dependentAsk Copilot to add a console.log; it should push back citing the instruction file. No pushback is a setup problem, not a content problem.
70–80% Copilot-side token reduction (claimed in PHASE1_COMPLETE.md)Target — not measuredRequires pilot usage data over 4–6 weeks. Nothing in the repo measures actual Copilot usage — no telemetry, no metrics API hook.
85%+ hallucination refusal rateTarget — not measuredRequires tracking outcomes across many real fixes in the pilot repos
20–30% faster PR fix speedTarget — not measuredRequires PR cycle-time measurement across pilot repos
Governed prompt is smaller than the raw promptIncorrectThe governed prompt is larger — it inlines the workflow. Efficiency shows in fewer wrong answers and review round-trips, not request size. Do not repeat the 70–80% figure.
Success Criteria

Metrics & Targets

IntelliJ-only repos are counted separately as uncovered — never counted as onboarded into runtime interception coverage.

MetricTarget
Repo onboarding100% of active repos receive the governance files
Technical prompt coverageEstablish baseline, then ≥95% during pilot on supported healthy adapters
Control-perimeter coverageEstablish managed-client inventory baseline; unsupported and disabled clients stay outside the numerator
Token impactMeasure completed-task tokens, retries and accepted output; no reduction target before baseline evidence
Security baseline coverage100% of repos include security guardrails
Console / debug reduction80% fewer unwanted console and debug review comments
PR fix speed20–30% faster fixes for common issues
Override safetyZero repo override loss
DriftGovernance drift fixed within one sync cycle
Prompt reuseApproved workflows used for common fixes
Compliance PR approval100% of governance changes reviewed by required owners
Reference

Source Documents

This page summarises the repository's markdown documentation. Each source below is authoritative for its own area.