A Repository Is Not an Authority: Provenance Gates for Coding-Agent Instructions
Treat AGENTS.md and similar coding-agent instructions as versioned inputs: verify provenance, pin reviewed guidance, constrain tool authority, and detect unsafe changes before agent runs.
On this page
A coding assistant needs local context: where tests live, how packages are organized, and which conventions help reviewers understand a change. Files such as AGENTS.md, CLAUDE.md, and repository-specific instructions make that context convenient. But convenience introduces a security question that ordinary code review does not always answer:
Who authorized this file to influence what the agent does?
The instruction file may be present in a repository, but repository presence is not the same as operational authority. A branch contributor can add guidance, a code generator can create a nested file, or a bot can modify a setup document. If the agent's host automatically ingests that text, the context boundary moves before anyone has decided whether the source is trustworthy.
I would solve this at the orchestration layer using an instruction provenance manifest. It records which instruction sources were accepted for a specific run, which were only displayed as untrusted context, and which were rejected. It does not rely on detecting “malicious-sounding” sentences, and it does not grant a repository file the power to change tool permissions.
This is a proposed engineering pattern, not a claim about an incident at a particular company or a shipped product. It complements my writing on containing prompt injection with capabilities and treating agent skills as dependencies. Here the narrower subject is automatically discovered repository instructions and the state transitions that make them safe to consume.
A realistic change that crosses two boundaries
Imagine a SaaS team maintaining a monorepo with a Next.js storefront and a small Python reporting service. A routine task imports a UI starter into apps/storefront. The imported files include a nested instruction document with helpful-looking commands and preferences. The agent's actual job is to update product-card rendering and verify that it builds.
The repository instruction recommends an unfamiliar setup task and says to skip a particular verification step to make the iteration faster. Those directions may be a legitimate convention in the starter, an obsolete instruction, or adversarial text. The application does not know which merely by reading Markdown.
Two different decisions are being conflated:
- May this text be considered while planning the work?
- May this text authorize running a command, reading secrets, changing CI, or contacting the network?
The answer to the second question must never come solely from the file. Even a reviewed repository instruction should not be able to expand the authority granted by the user and the host's execution policy.
The first decision is more nuanced. A trusted, protected repository may supply useful build instructions; a newly imported file may be helpful as reference data. But a file's provenance, scope, version, and review state should be recorded before it is promoted into the agent's instruction context.
Know how your actual agent discovers instruction files
There is no universal discovery rule across all coding agents and their versions.
GitHub documents support for repository and agent instruction files across different Copilot surfaces, including AGENTS.md, CLAUDE.md, and GEMINI.md in supported contexts. The support matrix differs by client and feature. GitHub's custom-instructions reference is the correct place to check a target integration rather than assuming every filename applies everywhere.
OpenAI's Codex prompting guide describes hierarchical discovery of AGENTS.md and related override files from configured locations and ancestor directories. That makes nested instructions useful, but also makes the exact working directory and selected configuration part of your security model.
For each agent runtime, capture the actual discovery contract in an adapter test: supported file names, ancestor traversal, nested precedence, content-size limits, whether symlinks are followed, what happens on missing files, and whether automatic discovery can be disabled or replaced. These are version-dependent behaviors. Do not copy an assumed behavior from one CLI into a different product.
An especially important integration rule follows: a policy scanner that runs after the agent has loaded its automatic instructions is too late. If your agent host cannot prevent unreviewed files from being ingested as privileged instructions, use a controlled workspace or supported loader configuration *before* the agent starts. If neither is feasible, run the task at a restricted privilege tier rather than claiming that a late warning prevented ingestion.
Treat instructions as a source-control supply chain
An instruction file is more like a versioned dependency than a system prompt. Its security-relevant identity should include more than its filename.
| Identity field | Why it matters |
|---|---|
| Repository and workspace identity | Avoid accepting a matching path from a different project |
| Canonical relative path | Distinguish root guidance from directory-specific guidance |
| Content digest | Detect changes that preserve the filename |
| Approved source revision | Trace the reviewed material back to a known state |
| Trusted approver and policy version | Explain who accepted the content and under which rules |
| Intended directory scope | Prevent a nested convention from applying to unrelated packages |
| Loader/adapter version | Know which discovery and precedence behavior was used |
| Effective execution profile | Show what tools were available independently of the text |
A digest proves that two byte sequences match. It does not prove a human reviewed those bytes, that their commands are safe, or that the file was never replaced after scanning. Approval needs an independently controlled registry or review record.
A Git commit hash is useful for tracing a source snapshot, but it is not itself a grant of authority. Branch protection, reviewer identity, and provenance of the approval process matter.
I would maintain the approval manifest outside the agent-writable worktree—for example, in protected deployment configuration or a security-owned service. A copy of that manifest checked into an untrusted pull request cannot be allowed to approve its own changes.
Architecture: decide before the context is assembled
~~~text Operator task + authenticated workspace identity | Trusted policy / approved source manifest | Repository snapshot (treat as untrusted) | Canonical-path + digest scanner | +------------+-------------+ | | | Approved Advisory Invalid or guidance content unknown source | | | | Optional bounded +--> quarantine | reference text +------------+ | Agent context construction | Capability policy / tool executor | Isolated task environment | Evidence + source manifest ~~~
The scanner does not need to decide whether a sentence “sounds dangerous.” It must establish source identity, byte integrity, and whether that identity matches approved policy. The context builder can then include approved instructions, or explicitly marked advisory content when the product permits that lower-trust input. The tool executor remains a separate, deterministic authorization boundary.
An agent that reads untrusted content may still be influenced by it. Labels and delimiters improve clarity but are not containment. OWASP's prompt-injection guidance recommends separating untrusted content, restricting privilege, and testing adversarial scenarios; it does not promise that prompt formatting will reliably neutralize attacks.
TypeScript: classify a snapshot against protected approvals
This is the core of an application-owned admission decision. It does not scan arbitrary filesystem paths or configure a real agent host; instead, it accepts a trusted scanner's immutable byte snapshots and an approval registry acquired from a protected source.
~~~typescript import { createHash, timingSafeEqual } from "node:crypto";
type Candidate = Readonly<{ relativePath: string; bytes: Uint8Array; kind: "regular" | "symlink" | "other"; }>;
type ApprovedInstruction = Readonly<{ relativePath: string; sha256: string; // 64 lowercase hexadecimal characters scope: string; // An approved repository-relative directory }>;
type Decision = | Readonly<{ kind: "approved"; path: string; scope: string }> | Readonly<{ kind: "advisory"; path: string; reason: string }> | Readonly<{ kind: "reject"; path: string; reason: string }>;
function canonicalRelativePath(path: string): boolean { if (!path || path.startsWith("/") || path.includes("\\") || path.includes("\0") || path.includes("//")) return false; return path.split("/").every( part => part.length > 0 && part !== "." && part !== ".." ); }
function digestMatches(actual: string, expected: string): boolean { if (!/^[a-f0-9]{64}$/.test(expected)) return false; const a = Buffer.from(actual, "hex"); const b = Buffer.from(expected, "hex"); return a.length === b.length && timingSafeEqual(a, b); }
export function classifyInstruction( file: Candidate, approved: ReadonlyMap<string, ApprovedInstruction>, maxBytes = 32 * 1024, ): Decision { const path = file.relativePath; if (!canonicalRelativePath(path) || file.kind !== "regular") { return { kind: "reject", path, reason: "invalid-path-or-file-type" }; } if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0 || file.bytes.length > maxBytes) { return { kind: "reject", path, reason: "oversized-file" }; }
const record = approved.get(path); if (!record) { return { kind: "advisory", path, reason: "no-protected-approval" }; } if (record.relativePath !== path || !canonicalRelativePath(record.scope)) { return { kind: "reject", path, reason: "bad-approval-record" }; }
const digest = createHash("sha256").update(file.bytes).digest("hex"); if (!digestMatches(digest, record.sha256)) { return { kind: "reject", path, reason: "approval-digest-mismatch" }; }
return { kind: "approved", path, scope: record.scope }; } ~~~
The comparison deliberately treats unknown files as advisory, not approved. That does not mean their content should automatically enter the model context; a separate product policy decides whether lower-trust reference material is needed for the task.
The code has important assumptions:
- A trusted scanner produced immutable bytes from the intended repository snapshot. It must verify the workspace identity, contain paths within the checkout, reject symlink traversal where relevant, and avoid time-of-check/time-of-use races.
- The protected approval store maps a path to an explicitly approved digest and scope. The example omits its authentication and signature checks.
- A production implementation must reject duplicate path identities and apply the same case-sensitivity semantics as its filesystem.
- The classifier does not grant shell execution or network access. Successful digest matching proves only that the file matches previously approved bytes.
A robust implementation either runs the agent on the same immutable snapshot that was classified or copies approved bytes into a controlled instruction channel. Scanning a mutable directory and then launching an unrestricted agent over that directory would recreate the race this design was meant to remove.
Python: authorize actions independently of the instruction text
Suppose a reviewed instruction says to run unit tests, and an unreviewed instruction says to publish a package. The application should not have to ask a model which document deserves more obedience. It should evaluate the operation against a separate execution profile.
~~~python from dataclasses import dataclass from typing import Literal
Action = Literal["run_check", "install_dependency", "publish_artifact"]
@dataclass(frozen=True) class TaskEnvelope: run_id: str approved_check_ids: frozenset[str] allow_dependency_install: bool allow_publish: bool
@dataclass(frozen=True) class Proposal: action: Action check_id: str | None = None
def authorize(proposal: Proposal, envelope: TaskEnvelope) -> bool: if not envelope.run_id: return False
if proposal.action == "run_check": return (proposal.check_id is not None and proposal.check_id in envelope.approved_check_ids)
if proposal.action == "install_dependency": return envelope.allow_dependency_install
if proposal.action == "publish_artifact": return envelope.allow_publish
return False # Unknown actions fail closed
envelope = TaskEnvelope( run_id="example-run", approved_check_ids=frozenset({"unit-storefront", "typecheck"}), allow_dependency_install=False, allow_publish=False, )
assert authorize(Proposal("run_check", "unit-storefront"), envelope) assert not authorize(Proposal("publish_artifact"), envelope) ~~~
This sketch makes one useful invariant obvious: the agent cannot grant itself the ability to publish by adding a line to AGENTS.md. The envelope comes from an authenticated operator request and a server-owned policy, not repository content or a model-generated claim.
In production, a named check ID must resolve to a protected, reviewed execution definition. Do not let unit-storefront resolve to an arbitrary repository script that was just edited in the pull request. Run untrusted builds and tests in a bounded, network-restricted environment with no production credentials. A Boolean flag is not a sandbox, a secure command runner, or human approval.
For a deeper discussion of those execution controls, see sandboxing generated code. The article on policy gates for agent side effects addresses the corresponding business-tool boundary.
Make a changed instruction visible in code review
Preflight admission controls a running agent. Repository governance controls how guidance changes over time. Both matter.
An organization using GitHub can require code-owner reviews for instruction files and the configuration that defines CI checks. GitHub's CODEOWNERS documentation explains why the owners file itself should also be protected. An illustrative pattern set is:
~~~text
Example .github/CODEOWNERS; replace with real teams and test matching.
Root and nested instruction files:
/AGENTS.md @example-org/agent-platform /AGENTS.md @example-org/agent-platform /CLAUDE.md @example-org/agent-platform /CLAUDE.md @example-org/agent-platform
Protect the review/automation configuration too:
/.github/ @example-org/security ~~~
This snippet uses illustrative organization identities and requires testing against actual paths and repository settings. Merely adding CODEOWNERS does not enforce review. Configure a suitable branch protection rule or repository ruleset that requires code-owner approval, and verify that the expected file owners are applicable and can review. GitHub's rulesets documentation provides the enforcement options.
Consider three types of instruction change separately:
| Change | Policy decision |
|---|---|
| Approved root instruction has only editorial edits | Recompute digest and require the configured reviewer before activation |
| Nested instruction arrives with a new dependency or generated directory | Keep lower-trust until its intended scope and provenance are reviewed |
| Instruction requests changes to CI, credentials, tool policy, or network rules | Treat as an operational policy proposal requiring separate authorization |
The first case is not always low risk; even a short wording change can redirect an agent. The approval process should prioritize affected behaviors and available capabilities, not use line count as the risk classifier.
Also pay attention to PR automation. GitHub warns that privileged pull_request_target or workflow_run paths can be dangerous when they fetch and execute untrusted changes. The GitHub Actions security guidance is explicit about the trust boundary. An instruction-file checker must not execute a PR-provided “validation helper” with privileged tokens.
Preserve a run manifest, not a story about why a file was trusted
When a reviewer later asks which guidance influenced a generated patch, an answer based on the agent's memory is insufficient. The orchestration layer should persist a small instruction manifest before the run starts.
An example shape:
~~~json { "run_id": "sample-run-42", "workspace_revision": "illustrative-commit", "adapter_profile": "codex-loader-tested-v1", "policy_revision": "instruction-policy-v3", "sources": [ { "path": "AGENTS.md", "disposition": "approved", "digest": "sha256:<digest-from-scanner>", "scope": "repository" }, { "path": "apps/storefront/AGENTS.md", "disposition": "advisory", "scope": "apps/storefront", "reason": "not-in-approval-registry" } ], "tool_profile": "read-build-test-no-network" } ~~~
The JSON is a schema illustration with placeholder identifiers and digest, not real evidence of a run. A real manifest should include trusted approval references, canonicalized identities, exact runtime/loader version, applicable source scopes, and retention controls. Keep it separate from the prompt itself.
A manifest has two uses. First, it makes policy auditable: which instruction source was accepted, denied, or only shown as data? Second, it supports debugging: a change in agent behavior can be correlated with a changed instruction digest or loader profile. It does not prove that the model followed an instruction or that a generated patch is correct.
Bind the manifest to the worktree revision, execution policy, and final pull-request commit. The acceptance-contract approach for AI-authored pull requests explains why evidence must be tied to the exact revision that will merge.
Test the boundary with controlled instruction mutations
I would validate this feature in two layers.
Deterministic tests should verify that an approved digest remains approved only for the specified path and scope, that modifying one byte rejects the former approval, that unknown paths remain unapproved, and that invalid encodings, oversized files, symlink entries, and duplicate canonical identities fail closed. Also test how the runtime handles case-insensitive filesystems, rename operations, and a file changed between scan and launch. The last case requires an integration-level immutable-snapshot test, not just a pure function.
Agent integration tests should compare runs with equivalent task inputs but different instruction provenance. For example, replace a safe project convention with an unapproved request to skip a required test. The expected result is not “the model definitely ignores the text”; it is that the host does not promote unapproved text to trusted guidance, and the protected executor still requires the test. Probe nested override behavior in every supported client version.
Other useful failure cases include a changed CODEOWNERS file in the same PR, a generated dependency hook that attempts network access, a hidden instruction in a tool result, and an interrupted preflight process. Refuse privileged execution when the required scanner, manifest store, or protected policy source is unavailable. When the application permits a lower-privilege offline task, record that downgrade explicitly.
No percentage should be presented as an observed defense rate without a repeatable experiment and measured results. A successful unit test of the classifier establishes policy behavior, not resistance of a model to every form of prompt injection.
Measure accepted context and denied authority separately
A useful dashboard should distinguish discovery, approval, tool-use policy, and outcome.
I would track instruction files discovered per run, approved versus advisory/rejected counts, digest mismatches, policy-store errors, preflight startup denials, unauthorized tool proposals, and attempts to modify protected instruction/CI paths. Use ratios with clear denominators: “rejected instruction sources per scanned source” is different from “blocked tool operations per proposed operation.”
For operations, monitor preflight latency, manifest-storage failures, agent task completion, and the incremental cost of isolated test environments. If approval becomes so slow that engineers routinely bypass it, that is a product-design problem to address with narrow, stable policies—not a reason to silently treat unknown files as trusted.
Use low-cardinality labels such as adapter profile, policy version, rejection category, and environment tier. Repository URL, exact file path, run ID, customer context, and raw instruction contents should live in restricted diagnostic records rather than general-purpose metric labels. The same principle appears in my telemetry export boundary.
Audit access to the approval manifest itself, and create an emergency revocation path. Once an instruction source is withdrawn, new runs should not accept it; active privileged runs may need to be stopped or downgraded according to a documented response policy. Revocation of a file approval should not be confused with deletion of a repository file.
What this design costs
A provenance gate adds a registry, a scanner, approval workflows, immutable snapshot handling, and adapter-specific tests. It is more involved than telling developers to “check your AGENTS.md.” That complexity is justified when coding agents work across branches, vendor code, generated projects, or repositories contributed to by people who should not automatically control the agent's execution environment.
For a private, tightly managed repository running an assistant with read-only tools, a lighter policy may be enough. For an agent that can install dependencies, modify CI, access secrets, or deploy, treat discovered instruction text as a supply-chain input and require an independently enforced capability boundary.
The essential separation is this:
Repository instructions help an agent understand how to work. They should not decide what the agent is authorized to do.
Keep the source provenance reviewable, keep the actual execution powers outside the Markdown, and make every exception attributable to a trusted decision.
Primary technical sources
- GitHub Copilot: supported custom instruction types
- OpenAI: Codex prompting guide and instruction discovery
- OWASP: LLM01 Prompt Injection
- GitHub: CODEOWNERS and required reviewers
- GitHub: Repository rulesets
- GitHub: Secure use of Actions
- Anthropic: Securing managed agent deployments
Topic provenance: I identified the subject through Viral Ruparel's October 26, 2026 article about coding-agent instruction files. This article uses a different hypothetical product scenario, its own instruction-manifest architecture, independent TypeScript and Python examples, original diagrams, and primary technical documentation.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article