
Dev Context Engineering
- 95 installs
- 73 repo stars
- Updated July 13, 2026
- vasilyu1983/ai-agents-public
Helps with ai & agent building tasks.
About
dev-context-engineering is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- dev-context-engineering
- AI & Agent Building
- AI-coding skill
Dev Context Engineering by the numbers
- 95 all-time installs (skills.sh)
- +9 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #4,606 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/vasilyu1983/ai-agents-public --skill dev-context-engineeringAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 95 |
|---|---|
| repo stars | ★ 73 |
| Last updated | July 13, 2026 |
| Repository | vasilyu1983/ai-agents-public ↗ |
What it does
Helps with ai & agent building tasks.
Files
Context Engineering
Use this skill to design repo-native agent context that is portable, high-signal, and maintainable. It owns the context model, migration path, maturity assessment, and context-graph discipline across AGENTS.md, runtime-specific layers, specs, rules, hooks, compiled markdown knowledge bases, and related artifacts.
Quick Reference
| Task | Use |
|---|---|
| Portable repo instructions | the agents-memory skill, references/fast-track-guide.md |
| Spec and plan flow | docs-ai-prd, dev-workflow-planning |
| Context graph design | references/context-graph-guide.md, python3 scripts/scan_context_artifacts.py --help, python3 scripts/validate_context_graph.py --help |
| Hot-tier staleness + supersession integrity checks | scripts/validate_context_graph.py (checks check_stale_tiers, check_supersession_integrity) |
| Query a context graph (PPR, BFS, fan-in, tier budget) | python3 scripts/query_context_graph.py <graph> --help (modes: --node, --impact, --rank, --ppr --seed, --tier-budget) |
| Compiled markdown knowledge layer | the docs-notes-retrieval skill, references/context-graph-guide.md, references/multi-repo-strategy.md |
| Multi-repo strategy | references/multi-repo-strategy.md, dev-context-multi-repo |
| Pick a framework (superpowers, GSD, Spec Kit, OpenSpec, …) | references/framework-selection-matrix.md |
| Regulated environment rollout | references/regulated-environment-patterns.md, assets/ai-agent-governance.md, assets/compliance-fca-emi.md |
When to Use
- Set up or modernize
AGENTS.md,CLAUDE.md, Copilot instructions, hooks, or agent rule layers. - Migrate a repo from ad hoc prompting to durable agent context.
- Decide what belongs in always-on context vs docs, retrieval, or on-demand artifacts.
- Build a context graph and loading-tier model for a repo.
- Define a maturity path for AI-assisted development across one repo or a portfolio.
- Design the operating model for a large compiled repo knowledge base where agents create and refresh repo descriptions, indexes, and reports from structured artifacts.
Route Elsewhere
- Writing the portable repo instructions themselves: use the
agents-memoryskill. - Repo-portfolio discovery and hub generation: use dev-context-multi-repo.
- Symbol-level code graphs and blast radius: use dev-context-code-graph.
- Task decomposition and verification plans: use dev-workflow-planning.
- Hooks, MCP, or subagent implementation details: use agents-hooks, agents-mcp, or agents-subagents.
Defaults
- Keep
AGENTS.mdas the portable baseline. - Add runtime-specific layers only when they unlock a real capability.
- Put only non-inferable constraints in always-on context.
- Use a small hot instruction layer plus a larger compiled markdown knowledge base instead of one giant manifest.
- Prefer better state and structure over more text.
- Let the LLM maintain cold knowledge layers and derived notes; humans review policy, safety, and architectural constraints.
- Prefer outputs as durable files that can be filed back into the repo context instead of living only in chat history.
- Run a documentation placement gate before creating new Markdown; prefer updating canonical docs or generated context artifacts over adding one-off files.
- Treat context changes like code changes: review, validate, and prune.
- Generate
context-graph.jsononce a repo reaches structured-context maturity. - Tool-set minimization: Only give agents the tools they actually need. If a human engineer cannot say which tool should be used for a given task, an AI agent will not do better. Start small; expand on demand.
- Resolver over accretion: when the hot layer starts growing to handle a new edge case, prefer a pointer-style resolver (description-matched skill selection) that loads the right document on demand. See references/context-resolver-pattern.md.
May 2026 Validation Stance
Current context engineering should treat context as an evolving system, not a larger prompt. The strongest source-backed principles are:
- Context is finite working memory: optimize for the smallest high-signal token set that changes the outcome, then load deeper evidence just in time.
- Context adaptation is a first-class engineering loop: generate, reflect, curate, and validate updates without letting iterative summaries collapse detail.
- Raw evidence must stay retrievable. Summaries, memories, and graph nodes are routing layers; they are not substitutes for source files, transcripts, artifacts, or primary docs.
- Memory needs lifecycle semantics: provenance, freshness, supersession, contradiction handling, and user or tenant scope. Use temporal graph memory only when temporal reasoning, relationship change, or cross-session continuity matters.
- Graph retrieval is conditional. Use direct reads or lexical search for simple lookup; use graph traversal, PPR, or community summaries only for relational, multi-hop, or global sensemaking questions.
- Tool and context surfaces should be minimal and governed. More tools or more always-on rules create ambiguity unless the selection boundary is explicit.
Multi-Tool Composition
Teams that ship fastest use the right tool for each task rather than forcing one agent to do everything. As of May 2026, the most effective pattern is:
| Tool | Best For | Context Model |
|---|---|---|
| Cursor / IDE agent | Day-to-day editing, inline completions, tab-to-accept, quick refactors | IDE-native: open files + project index |
| Claude Code | Complex agentic tasks, multi-file changes, agent teams, code review, architecture | CLI: AGENTS.md + .claude/rules + skills + subagents |
| Codex | Parallel background work, batch processing, CI-adjacent tasks | Threads: AGENTS.md + .codex/agents + sandboxed workers |
How to keep context consistent across tools: 1. AGENTS.md is the portable baseline — all three tools read it. 2. Runtime-specific layers (.claude/rules/, .codex/agents/, .cursor/rules/) extend the baseline for each tool's strengths. 3. docs/ in the repo is universally readable — invest knowledge there, not in tool-specific memory. 4. Use dev-context-multi-repo to keep multi-repo context aligned across tools.
Anti-pattern: Duplicating conventions in Cursor rules, Claude rules, AND Codex agents. Write it once in AGENTS.md or docs/, then reference it.
Stack on top of the IDE layer when discipline drift or feature ambiguity is the bottleneck:
| Layer | Role | Pick from |
|---|---|---|
| L0 portable baseline | Cross-tool conventions | AGENTS.md |
| L1 runtime-specific | Tool-specific extensions | .claude/rules/, .codex/agents/, .cursor/rules/, .github/copilot-instructions.md, .clinerules/, Aider CONVENTIONS.md |
| L2 capability / methodology | On-demand or enforced discipline | Claude Code Skills · superpowers (obra/superpowers) · GSD (gsd-build/get-shit-done) |
| L3 artifact pipeline | Spec → plan → tasks → code | GitHub Spec Kit (.specify/specs/) · OpenSpec (Fission-AI, openspec/changes/) |
L0 is mandatory; L1 is mandatory for tools that don't read AGENTS.md natively; L2 and L3 are optional but high-leverage when their named symptoms are present. Full decision matrix, stack recipes, and anti-stacks in references/framework-selection-matrix.md.
Workflow
1. Identify the toolchain, repo shape, and the behaviors that need to be influenced. 2. Define the portable baseline, the compiled knowledge layer, and the minimum runtime-specific layers needed. 3. Separate hot instructions from warm compiled knowledge and cold raw evidence the agent can inspect on demand. 4. Install the right supporting artifacts: specs, plans, hooks, rules, subagents, docs, and index pages that make the compiled layer navigable. 5. Decide which answers or analyses should become durable markdown files, diagrams, or reports instead of one-off chat output, and place them under the repo's docs governance model. 6. Generate and validate a context graph when the repo has enough artifacts to justify it. 7. Run health checks over the context system for stale dependencies, missing summaries, inconsistent claims, and dead links. 8. Score maturity, then decide whether the next step is onboarding, pruning, or automation.
ASCII Flow
context engineering request
-> identify toolchain, repo shape, and target agent behaviors
-> define portable baseline in AGENTS.md
-> split layers
+-- hot -> non-inferable execution policy
+-- warm -> compiled docs, hubs, indexes, context graph
+-- cold -> raw evidence and primary artifacts
-> add runtime-specific rules only where they unlock capability
-> run docs placement and context hygiene gates
-> validate graph, freshness, links, and contradictions
-> decide onboarding, pruning, automation, or maturity next stepCore Decisions
Cross-Tool Context Model
Use layers intentionally:
AGENTS.mdfor hot shared execution policyCLAUDE.mdand.claude/*only for Claude-specific behavior.github/*only for GitHub or Copilot-specific behavior- compiled markdown hubs, index pages, and context graphs for reusable repo knowledge
- raw evidence packs for articles, repos, transcripts, screenshots, and other source captures
- docs and specs for on-demand context
- external knowledge via skills, MCP, or runtime retrieval
Do not assume one tool’s memory model maps cleanly onto another.
At small and medium corpus sizes, a maintained index plus concise summaries is often enough; do not add RAG just because a knowledge base exists.
What Belongs in Context
Keep always-on context for:
- custom commands and repo workflows
- safety or compliance constraints
- fragile architecture boundaries
- known failure modes and approval rules
- cross-repo data flows that are hard to infer locally
Keep the compiled knowledge base for:
- domain summaries and concept pages
- cross-repo maps and architecture views
- volatile tool or product findings that should be re-checked but are still worth preserving
- derived outputs such as reports, diagrams, and slide notes that should compound over time
Keep out:
- README-style summaries
- big file inventories
- dependency lists the agent can inspect
- duplicated coding-style philosophy
- docs that add no execution constraint
- raw source dumps that belong in evidence folders instead of the hot instruction layer
Documentation Placement Resolver
Before creating a context artifact, choose the smallest durable home:
- hot instruction:
AGENTS.md/CLAUDE.mdfor short execution policy and pointers only - canonical docs:
docs/tech/,docs/architecture/,docs/api/, or equivalent for stable truth - operational docs:
docs/operations/ordocs/runbooks/for procedures and incident/release steps - reports and plans:
docs/reports/,docs/specs/, ordocs/plans/with lifecycle state and integration path - generated context:
docs/context/orcontext/with structured inputs and rebuild commands - raw evidence:
raw/,evidence/, or repo-specific captures excluded from hot context
If the artifact has no owner, lifecycle, index link, or rebuild path, do not create a new Markdown file. Update the closest canonical doc or keep the result in the task thread.
Knowledge Base Pattern
The strongest default is a three-layer repo-native system:
- hot layer: portable instructions and execution policy
- compiled layer: LLM-maintained markdown with summaries, backlinks, concept pages, and index files
- raw layer: source captures and evidence the agent can revisit when a compiled claim needs re-verification
Humans should mostly edit the hot layer and review the compiled layer. The compiled and raw layers can be largely agent-maintained if validation and review gates are in place.
For portfolio hubs, add one more practical rule:
- structured artifacts such as profile JSON, graph JSON, and freshness reports should be the compiler inputs for markdown pages, not sidecars that drift independently
This is how you keep repo descriptions, concept notes, and system maps synchronized at scale.
Context Graph
Use a context graph to map relationships between:
- instructions
- rules
- specs
- plans
- hooks
- subagents
- references and assets
Generate it when the repo reaches L2+ maturity and use it to assess loading tiers, blast radius, and stale dependencies before changing core artifacts.
The context graph complements the compiled markdown layer. Use the graph for relationship integrity and loading-tier analysis, then publish the useful findings back into markdown notes or reports.
When the repo is a native/mobile codebase, pair this skill with:
- dev-context-multi-repo to classify the repo correctly from project files such as
project.yml,.xcodeproj, orPackage.swift - dev-context-code-graph to build the single-repo symbol graph from Swift or mixed-language source after generated build trees are excluded
Spec-Driven Development
Use full spec-driven development when ambiguity would otherwise cause agent drift:
- specify what
- plan how
- decompose into bounded tasks
- implement with the right context attached
Use direct prompting for small fixes and low-ambiguity work.
For recurring hub maintenance, treat page generation as a compiler pass:
- define the source artifacts
- define the target page shape
- define what gets regenerated incrementally
- define the lint or health checks that block publication
Regulated Environments
In regulated environments, context engineering must preserve:
- auditability
- separation of duties
- sensitive-data boundaries
- provider portability
- named human accountability
If those requirements are real, treat context artifacts as part of the control surface, not just helper docs.
Output Modes
Default to one of these:
- Repo context package:
portable baseline, runtime-specific layers, and supporting artifact map.
- Knowledge-base operating model:
hot instructions, compiled markdown layer, raw evidence layout, and maintenance loop.
- Hub compiler design:
source artifacts, generated page types, incremental rebuild strategy, and validation gates.
- Migration plan:
current-state issues, target shape, phased rollout, and validation steps.
- Maturity assessment:
current level, blockers, and next infrastructure step.
- Regulated rollout brief:
control requirements, artifact placement, and review gates.
Known Traps
- Pushing too much policy, process, and repo knowledge into always-on instructions until agents ignore or truncate the layer that actually matters.
- Building runtime-specific rule stacks before the portable baseline is stable, which guarantees drift across tools.
- Treating a compiled markdown hub as static documentation instead of a maintained product with freshness and validation loops.
- Shipping large context changes without a clear loading-tier model, so hot instructions and cold evidence get mixed together.
- Assuming tool abundance helps by default instead of reducing the tool set to the smallest model the team can actually govern.
- Creating a new Markdown file for every useful answer instead of routing it into the existing docs, report, or generated-context lifecycle.
- Mixing operational runbooks, agent hot memory, canonical docs, and generated context until no file has clear authority.
- LLM-summarizing raw evidence before retrieval. Measured failure mode: on LongMemEval, verbatim-text retrieval scores 96.6% R@5 while LLM-extracted memory systems score 30-45% on ConvoMem — preemptive summarization throws away the context that made the answer findable. Keep the raw layer raw. (source
benchmarks/BENCHMARKS.md)
Anti-Patterns
- One giant context file.
- Using
AGENTS.mdas a general knowledge base instead of a hot instruction layer. - Blindly generating context from docs without pruning.
- Using more text instead of fixing state and structure.
- Locking policy to one vendor format.
- Treating context as static instead of a maintained system.
- Keeping execution-critical guidance outside the repo.
- Letting useful answers disappear in chat instead of filing them back into the compiled layer.
- Filing useful answers as unindexed one-off Markdown files with no owner, lifecycle state, or canonical parent.
- Adding heavy retrieval infrastructure before maintaining indexes, summaries, and basic health checks.
- Treating JSON, graphs, and markdown pages as separate truth systems instead of a compiler pipeline.
Navigation
- Core references: references/fast-track-guide.md, references/framework-selection-matrix.md, references/information-routing-rules.md, references/context-resolver-pattern.md
- Context graph and multi-repo strategy: references/context-graph-guide.md, references/multi-repo-strategy.md
- Regulated and governed rollout: references/regulated-environment-patterns.md, assets/ai-agent-governance.md, assets/data-handling-gdpr-pci.md, assets/compliance-fca-emi.md, assets/pr-template-ai-disclosure.md, assets/fca-compliance-gate.yml
- Scripts and schema:
scripts/scan_context_artifacts.py,scripts/validate_context_graph.py,scripts/query_context_graph.py, schemas/context-graph.schema.json - Related skills: the
agents-memoryskill, docs-ai-prd, dev-workflow-planning, agents-hooks, agents-mcp, agents-subagents, agents-swarm-orchestration, dev-context-multi-repo, dev-context-code-graph
Fact-Checking
- Known bugs, regressions, framework/compiler/runtime footguns, and version-specific crash or workaround guidance must be verified against current primary web sources before being treated as current fact.
- External source mapping lives in data/sources.json.
- Product capabilities, runtime semantics, and regulator guidance are volatile; verify current primary sources before making definitive claims about tools or compliance timelines.
- Remove or mark any claim that cannot be re-verified from a primary source.
Example template for a regulated fintech. Swap rule IDs, regime references (FCA/EMI, SM&CR, SS1/23, IBS register), and gate steps for your own regulatory context before use. This is illustrative scaffolding, not legal or compliance advice.
AI Agent Governance Rules
Copy this file to .claude/rules/ai-agent-governance.md in every repository.This is a MANDATORY rule file for organizations using AI coding agents.
Approved AI Tools
Only the following AI coding tools are approved for use:
| Tool | Approved Use | Restrictions |
|---|---|---|
| Claude Code | Interactive development, planning, code review, subagents | No auto-merge, no deployment |
| Codex | Async batch tasks, issue triage, test generation | Sandboxed execution only |
| Cursor | IDE-assisted editing (supplementary) | No autonomous mode on regulated code |
| GitHub Copilot | Inline suggestions (supplementary) | Review all suggestions before accepting |
Unapproved tools must not be used on company repositories without security team review.
Usage Restrictions by Environment
| Environment | AI Agent Allowed | Restrictions |
|---|---|---|
| Local development | Yes | No real customer data in prompts |
| CI/CD pipelines | Codex only (sandboxed) | Read-only access, no deployments |
| Staging | Yes (via approved tools) | Synthetic data only |
| Production | No direct access | AI agents never touch production systems |
| Production debugging | Sanitized logs only | Strip PII before sharing with agents |
Disclosure Requirements
Every PR
- AI tools used must be declared in the PR description
- Role of AI must be specified (generated, reviewed, tested, debugged)
- Human verification checklist must be completed
Quarterly Reporting
- Aggregate AI tool usage metrics reported to engineering leadership
- Defect rates in AI-assisted vs non-AI PRs tracked
- Cost metrics (token usage, subscription costs) reported
Incident Reporting
- AI tool failures affecting development velocity: report to engineering lead
- AI-generated code causing production incidents: report to CTO + compliance
- Data exposure via AI tools: report to security team + DPO immediately
AI Tool Configuration
Required Settings
- Telemetry: Review and approve data sharing settings
- Context: portable
AGENTS.mdbaseline plus tool-specific files only where needed - Rules: Mandatory compliance rules installed (compliance-fca-emi.md, data-handling-gdpr-pci.md)
- Hooks: Pre-commit validation hooks enabled where available
Prohibited Configurations
- Do not disable security-related hooks or pre-commit checks
- Do not configure AI tools to bypass code review
- Do not grant AI tools write access to production branches
- Do not share API keys for AI tools across personal and company use
Training Requirements
Before using AI coding agents on company repositories:
1. Complete AI tool governance briefing (provided by engineering leadership) 2. Review this governance document and the companion compliance rules 3. Understand the PR AI disclosure template and complete it consistently 4. Know the escalation path for AI-related incidents
Inventory and Tracking
- All repositories using AI coding agents must be registered in the AI tool inventory
- AI-generated code artifacts in critical paths must be flagged in the model risk register
- New AI tool adoptions require security team review and compliance sign-off
- Annual review of approved tool list and governance policies
Example template for a regulated fintech. Swap rule IDs, regime references (FCA/EMI, SM&CR, SS1/23, IBS register), and gate steps for your own regulatory context before use. This is illustrative scaffolding, not legal or compliance advice.
FCA/EMI Compliance Rules for AI Coding Agents
Copy this file to .claude/rules/compliance-fca-emi.md in every repository.This is a MANDATORY rule file for FCA-regulated Electronic Money Institutions.
Audit Trail
- All commits MUST be signed (GPG or SSH key)
- Force-push is PROHIBITED on all protected branches
- Use merge commits to main/master (no squash, no rebase) to preserve full history
- Every PR must use the AI disclosure template (see pr-template-ai-disclosure.md)
- Commit messages must follow conventional commit format:
type(scope): description
Separation of Duties
- AI agents MUST NOT approve pull requests
- AI agents MUST NOT merge to production branches
- AI agents MUST NOT trigger deployments
- The PR author MUST NOT be the sole reviewer (four-eyes principle)
- Code reviewer MUST be a different person from the developer who used the AI agent
- Security-critical changes (auth/, payments/, crypto/, compliance/) require an additional security reviewer
Prohibited Actions
- NEVER auto-merge pull requests to production branches
- NEVER bypass branch protection rules
- NEVER commit without signing
- NEVER store real customer data in code, tests, comments, or context files
- NEVER include credentials, API keys, or connection strings in committed files
- NEVER disable security scanning gates in CI/CD
AI-Generated Code Tracking
- All PRs involving AI-generated code must declare AI involvement in the PR description
- AI tools used must be listed (Claude Code, Codex, Cursor, Copilot)
- Files that are primarily AI-generated must be identified
- Human verification checklist must be completed before merge approval
Model Risk Inventory
- AI-generated code artifacts are subject to SS1/23 model risk management principles
- Track AI-generated components in the team's model risk register
- Defect rates for AI-generated code must be monitored and reported quarterly
- Any AI-generated code in critical paths (auth, payments, crypto) requires enhanced review
SM&CR Accountability
- The designated Senior Manager (SMF) is accountable for AI tool governance
- "The AI wrote it" is not an acceptable explanation for defects or compliance failures
- Developers must understand all AI-generated code they approve
- Training on AI tool usage and governance is required for all certified persons
Operational Resilience
- AI tool unavailability is a scenario in operational resilience testing
- Manual development fallback procedures must be documented and tested quarterly
- AI tool providers (Anthropic, OpenAI) are listed in the IBS dependency register
- Portability: AGENTS.md format supports multiple AI tools (Claude Code + Codex)
Example template for a regulated fintech. Swap rule IDs, regime references (FCA/EMI, SM&CR, SS1/23, IBS register), and gate steps for your own regulatory context before use. This is illustrative scaffolding, not legal or compliance advice.
Data Handling Rules: GDPR and PCI DSS
Copy this file to .claude/rules/data-handling-gdpr-pci.md in every repository.This is a MANDATORY rule file for organizations handling personal data or payment card data.
Safe Data Categories
These categories are safe to include in agent context, code comments, specs, and plans:
- Code abstractions and design patterns
- Business logic descriptions (without real customer examples)
- Synthetic test data with clearly fake values
- Architecture diagrams and data flow descriptions
- API endpoint definitions and schemas
- Error codes and status definitions
- Configuration templates with placeholder values
- Performance metrics and SLAs (anonymized)
Prohibited Data Categories
NEVER include any of the following in agent context, prompts, code, comments, commit messages, PR descriptions, specs, plans, or any file processed by AI agents:
Personal Data (GDPR)
- Names, email addresses, phone numbers of real individuals
- Physical addresses, IP addresses, location data
- Dates of birth, national insurance numbers, passport numbers
- Financial account details (bank account numbers, sort codes)
- Health data, biometric data, genetic data
- Racial/ethnic origin, political opinions, religious beliefs
- Trade union membership, sexual orientation
- Any data that could identify a living individual directly or indirectly
Payment Card Data (PCI DSS)
- Primary Account Numbers (PANs) — real or realistic-looking
- Cardholder names associated with card data
- Card expiry dates associated with card data
- CVV/CVC/CAV codes
- PIN blocks or encrypted PIN data
- Track data (magnetic stripe or chip equivalent)
- Service codes
Credentials and Secrets
- API keys, tokens, passwords
- Database connection strings with credentials
- Private keys (SSL, SSH, GPG)
- OAuth client secrets
- Webhook signing secrets
- Encryption keys or key material
Test Data Guidelines
When tests need data that resembles real data:
# Good: Clearly synthetic
name: "Test User Alpha"
email: "test-alpha@example.com"
card: "4242 4242 4242 4242" (Stripe test card)
phone: "+44 7700 900000" (Ofcom test range)
# Bad: Could be real
name: "John Smith"
email: "john.smith@gmail.com"
card: "4532 1234 5678 9012" (looks real)
phone: "+44 7911 123456" (could be real)Context Filtering Patterns
When AI agents work with code that processes sensitive data:
- Reference data by TYPE, not by VALUE: "the customer's email field" not "john@example.com"
- Use schema definitions instead of data samples
- Describe transformations abstractly: "hash the PAN before storage" not "hash 4532..."
- Link to data flow documentation rather than embedding data examples
Incident Response
If sensitive data is accidentally committed:
1. Do not push if not yet pushed 2. Immediately notify the security team and DPO 3. Use git filter-branch or BFG Repo-Cleaner to remove from history 4. Rotate any exposed credentials immediately 5. Document the incident per operational resilience framework 6. Assess if a breach notification is required (72-hour GDPR window)
# Example template for a regulated fintech. Swap rule IDs, regime references
# (FCA/EMI, SM&CR, SS1/23, IBS register), and gate steps for your own
# regulatory context before use. Illustrative scaffolding, not compliance advice.
#
# FCA Compliance Gate — GitHub Actions Workflow
#
# Copy this file to `.github/workflows/fca-compliance-gate.yml` in every repository.
# This workflow enforces FCA/EMI compliance requirements on all pull requests.
#
# Prerequisites:
# - Branch protection rules configured (require signed commits, no force-push)
# - gitleaks installed or available as GitHub Action
# - Semgrep or CodeQL configured for SAST
# - PR template with AI disclosure (see pr-template-ai-disclosure.md)
name: FCA Compliance Gate
on:
pull_request:
branches: [main, master, develop]
push:
branches: [main, master]
permissions:
contents: read
pull-requests: read
security-events: write
jobs:
signed-commits:
name: Verify Signed Commits
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check all commits are signed
run: |
UNSIGNED=$(git log --format='%H %G?' origin/main..HEAD 2>/dev/null | grep -E ' N$' | head -5)
if [ -n "$UNSIGNED" ]; then
echo "::error::Unsigned commits detected. All commits must be signed (GPG or SSH)."
echo "$UNSIGNED"
exit 1
fi
echo "All commits are signed."
secrets-detection:
name: Secrets Detection
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Run gitleaks
uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
sast-scanning:
name: Static Analysis
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run Semgrep
uses: semgrep/semgrep-action@v1
with:
config: >-
p/security-audit
p/secrets
p/owasp-top-ten
env:
SEMGREP_APP_TOKEN: ${{ secrets.SEMGREP_APP_TOKEN }}
pii-detection:
name: PII Pattern Detection
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Scan for PII patterns in changed files
run: |
# Get changed files
CHANGED_FILES=$(git diff --name-only origin/main...HEAD 2>/dev/null || git diff --name-only HEAD~1)
# PII patterns to detect (conservative, high-precision)
PII_PATTERNS=(
'[0-9]{2}/[0-9]{2}/[0-9]{4}' # UK date format (potential DOB)
'[A-Z]{2}[0-9]{6}[A-Z]' # UK National Insurance Number
'[0-9]{4}[[:space:]][0-9]{4}[[:space:]][0-9]{4}[[:space:]][0-9]{4}' # Card number format
'password[[:space:]]*=[[:space:]]*["\x27][^"\x27]+' # Hardcoded passwords
)
FOUND=false
for file in $CHANGED_FILES; do
[ ! -f "$file" ] && continue
# Skip binary files and known safe files
case "$file" in
*.png|*.jpg|*.gif|*.ico|*.woff|*.lock|*.sum) continue ;;
esac
for pattern in "${PII_PATTERNS[@]}"; do
if grep -qE "$pattern" "$file" 2>/dev/null; then
echo "::warning file=$file::Potential PII pattern detected: $pattern"
FOUND=true
fi
done
done
if $FOUND; then
echo "::error::PII patterns detected in changed files. Review findings above."
echo "If these are false positives (e.g., test data), add inline comments explaining why."
exit 1
fi
echo "No PII patterns detected."
ai-disclosure:
name: AI Disclosure Check
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
steps:
- name: Check PR body for AI disclosure
env:
PR_BODY: ${{ github.event.pull_request.body }}
run: |
if [ -z "$PR_BODY" ]; then
echo "::error::PR description is empty. Please use the PR template with AI disclosure section."
exit 1
fi
# Check for AI disclosure section
if ! echo "$PR_BODY" | grep -qi "AI.*Involvement\|AI.*Disclosure\|AI.*Tools.*Used"; then
echo "::error::PR description missing AI Involvement Disclosure section."
echo "Please use the PR template and complete the AI disclosure checklist."
exit 1
fi
# Check for human verification checklist
if ! echo "$PR_BODY" | grep -qi "Human.*Verification\|Verification.*Checklist"; then
echo "::warning::PR description may be missing the Human Verification Checklist."
fi
echo "AI disclosure section found in PR description."
dependency-scan:
name: Dependency Vulnerability Scan
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run dependency audit
run: |
# Detect package manager and run audit
if [ -f "package-lock.json" ] || [ -f "yarn.lock" ]; then
npm audit --audit-level=high 2>/dev/null || echo "::warning::npm audit found vulnerabilities"
elif [ -f "requirements.txt" ] || [ -f "Pipfile.lock" ]; then
pip install pip-audit 2>/dev/null && pip-audit 2>/dev/null || echo "::warning::pip-audit found vulnerabilities"
elif [ -f "go.sum" ]; then
go install golang.org/x/vuln/cmd/govulncheck@latest 2>/dev/null && govulncheck ./... 2>/dev/null || echo "::warning::govulncheck found vulnerabilities"
else
echo "No recognized package manager found. Skipping dependency audit."
fi
compliance-summary:
name: Compliance Summary
runs-on: ubuntu-latest
needs: [signed-commits, secrets-detection, sast-scanning, pii-detection, ai-disclosure, dependency-scan]
if: always()
steps:
- name: Report compliance status
run: |
echo "## FCA Compliance Gate Results"
echo ""
echo "| Check | Status |"
echo "|-------|--------|"
echo "| Signed Commits | ${{ needs.signed-commits.result }} |"
echo "| Secrets Detection | ${{ needs.secrets-detection.result }} |"
echo "| SAST Scanning | ${{ needs.sast-scanning.result }} |"
echo "| PII Detection | ${{ needs.pii-detection.result }} |"
echo "| AI Disclosure | ${{ needs.ai-disclosure.result }} |"
echo "| Dependency Scan | ${{ needs.dependency-scan.result }} |"
# Fail if any critical check failed
if [[ "${{ needs.signed-commits.result }}" == "failure" ]] || \
[[ "${{ needs.secrets-detection.result }}" == "failure" ]] || \
[[ "${{ needs.sast-scanning.result }}" == "failure" ]] || \
[[ "${{ needs.pii-detection.result }}" == "failure" ]] || \
[[ "${{ needs.ai-disclosure.result }}" == "failure" ]]; then
echo "::error::One or more compliance gates failed. PR cannot be merged."
exit 1
fi
echo "All compliance gates passed."
Example template for a regulated fintech. Swap rule IDs, regime references (FCA/EMI, SM&CR, SS1/23, IBS register), and gate steps for your own regulatory context before use. This is illustrative scaffolding, not legal or compliance advice.
Pull Request Template with AI Disclosure
Copy this file to .github/pull_request_template.md in every repository.## Summary
<!-- Brief description of what this PR does and why -->
## Changes
<!-- Bulleted list of changes -->
-
## AI Involvement Disclosure
### AI Tools Used
<!-- Check all that apply -->
- [ ] Claude Code
- [ ] Codex
- [ ] Cursor
- [ ] GitHub Copilot
- [ ] Other: ___
- [ ] No AI tools used
### AI Role
<!-- Check all that apply -->
- [ ] Generated code
- [ ] Reviewed/analyzed code
- [ ] Generated tests
- [ ] Assisted debugging
- [ ] Generated documentation
- [ ] Planned implementation
### Files Primarily AI-Generated
<!-- List files where >50% of the code was AI-generated, or write "None" -->
-
### Human Verification Checklist
<!-- All boxes must be checked before merge approval -->
- [ ] I have read and understand all AI-generated code in this PR
- [ ] I have verified the code works as intended (ran tests, manual testing)
- [ ] I have reviewed for security concerns (injection, auth, data exposure)
- [ ] I have checked compliance with coding standards and architecture patterns
- [ ] I have verified no sensitive data (PII, credentials, card data) is included
- [ ] I have confirmed the code does not introduce unintended side effects
## Test Plan
<!-- How was this tested? -->
- [ ] Unit tests added/updated
- [ ] Integration tests added/updated
- [ ] Manual testing performed
- [ ] No testing needed (docs/config only)
## Compliance
<!-- For changes to auth/, payments/, crypto/, compliance/ directories -->
- [ ] Security review requested (if applicable)
- [ ] Compliance review requested (if applicable)
- [ ] N/A — no security-critical changesContext Graph Guide
A practical reference for generating, reading, and using the per-repo context graph produced by the dev-context-engineering skill.
Table of Contents
- What Is a Context Graph
- Generating the Graph
- Loading Tiers
- Query Mode Taxonomy
- Relationship Detection
- Integration with CDLC
- Context Impact Analysis
- Maturity Model Integration
- Related References
---
What Is a Context Graph
A context graph is a per-repo JSON graph (context-graph.json) that maps every context artifact in a repository and the relationships between those artifacts.
Artifacts include: AGENTS.md, CLAUDE.md, coding rules, specs, plans, subagent definitions, hooks, and other files that shape how AI coding agents understand and operate inside the repo.
The graph is produced by running scan_context_artifacts.py against a repository root. It complements the portfolio-level knowledge graph maintained by the dev-context-multi-repo skill, which aggregates context signals across many repositories. The per-repo graph gives fine-grained visibility into a single codebase; the portfolio graph gives cross-repo comparisons.
Why it matters. AI agents load context on every turn. Without a graph, agents reload all context blindly, wasting tokens and risking stale or conflicting instructions. With a graph, the loading tier of each artifact is explicit, relationships are traceable, and changes can be evaluated for downstream impact before context is reloaded.
---
Generating the Graph
Run scan_context_artifacts.py from any environment that has Python 3:
python3 /path/to/scan_context_artifacts.py /path/to/repo
# Output: /path/to/repo/context-graph.jsonThe script walks the repository tree, identifies artifacts by path pattern and file name, classifies each into a loading tier, and detects edges between artifacts by scanning file content. The output is a single JSON file at the repository root.
Validate the result immediately after generation:
python3 /path/to/validate_context_graph.py /path/to/repo/context-graph.json --repo /path/to/repo
# Optional: --output reports/context-graph-validation.json12 artifact types detected:
| Type | Matched paths |
|---|---|
agents_md | AGENTS.md at root |
claude_md | CLAUDE.md at root |
rule | .claude/rules/*.md |
spec | docs/specs/*.md, specs/*.md, SPEC.md |
plan | docs/plans/*.md, plans/*.md |
subagent | .claude/agents/*.md, .github/agents/*.md |
hook | Entries under .claude/hooks/ |
copilot_instructions | .github/copilot-instructions.md, .github/instructions/*.md, .github/instructions/*.instructions.md |
github_agent | .github/agents/*.md |
reference | docs/references/*.md |
asset | assets/**/* |
skill | skills/*/SKILL.md |
Re-run the script whenever artifacts are added, renamed, or removed. For automated freshness, add it to CI or a git commit hook (see Maturity Model Integration).
---
Loading Tiers
Every node in the graph carries a loading_tier field that tells agents when to load it:
| Tier | Label | Artifact types | Load policy |
|---|---|---|---|
| L1 | L1_always | agents_md, claude_md, hook, root copilot_instructions | Loaded on every agent turn, unconditionally |
| L2 | L2_on_demand | rule, subagent, path-scoped copilot_instructions, github_agent | Loaded when the agent determines it is relevant to the current task |
| L3 | L3_referenced | spec, plan, reference, asset, skill | Pulled only when explicitly referenced by the task, another artifact, or an agent instruction |
Loading tiers exist to control token budgets. L1 nodes are always in context; L2 and L3 nodes are lazy-loaded. Misclassifying a frequently-needed spec as L3 will cause agents to miss it; misclassifying a large asset file as L1 will waste tokens every turn.
---
Query Mode Taxonomy
<!-- Source: Microsoft GraphRAG (Local / Global / DRIFT / Basic). Aligned with the loading-tier model above and the portfolio query taxonomy in dev-context-multi-repo/references/knowledge-graph-patterns.md §15. -->
Loading tiers say when to load an artifact. Query modes say how to find it. Microsoft GraphRAG's four canonical modes map onto this skill's context-graph operations:
| Mode | Question shape | Default route | Loading tier interaction |
|---|---|---|---|
| Basic | "What does this rule say?" "Show me the spec for X" | Direct file read by id or path | Pulls one L2/L3 artifact on demand |
| Local | "What rules apply to this subagent?" "What artifacts reference CLAUDE.md?" | Edge traversal at 1–2 hops in context-graph.json | L1 nodes always in scope; traversal pulls L2/L3 neighbors |
| DRIFT | "Pull all context relevant to this task" | Personalized PageRank from a seed (the task's anchor artifact); see dev-context-multi-repo/references/knowledge-graph-patterns.md §13 | L1 plus the highest-PPR L2/L3 nodes within token budget |
| Global | "What's the overall context architecture?" "How is this repo's context organized?" | Community detection (Leiden) over the artifact graph; see knowledge-graph-patterns.md §14 | Returns community summaries, not raw artifacts |
For most per-repo work, Basic and Local are sufficient — the artifact graph in a single repo rarely needs PPR or community detection. DRIFT becomes useful when the L2/L3 layer has 50+ artifacts and the agent needs to pull "task-relevant context" without reading everything. Global becomes useful when documenting the context system itself for new contributors.
The cheapest mode that answers the question wins. Escalate only when the question genuinely needs it.
---
Relationship Detection
The current scanner auto-detects 4 edge types by inspecting file content:
| Edge type | Detection rule |
|---|---|
imports | Explicit !include, # @import, or @path directive referencing another artifact path |
references | Markdown link [text](path) where the path resolves to another artifact in the graph |
delegates_to | A bracketed skill mention or (skill:...) reference that resolves to a discovered skill node |
enforces | A hook node that references a rule node by filename stem in its trigger or command |
The schema also reserves documents, triggers, validates, overrides, and extends for future deterministic scanners or manual augmentation, but scan_context_artifacts.py does not emit those relations today.
Each edge in context-graph.json has the form:
{
"source": "relative-path-derived-node-id",
"target": "relative-path-derived-node-id",
"relation": "references"
}Edges are directional. source → target means the source artifact depends on or is aware of the target. Backward traversal (finding all artifacts that depend on a given artifact) is used for impact analysis (see Context Impact Analysis).
Missing edges are a common finding on first scan. If a rule is never referenced by any other artifact, agents cannot discover it through graph traversal and must rely on L1 or L2 loading alone.
---
Integration with CDLC (Context-Driven LLM Collaboration)
The context graph plugs directly into the four CDLC phases:
Generate. scan_context_artifacts.py produces context-graph.json. Run it once at repo setup, then re-run on any structural change to the context layer.
Evaluate. Inspect the graph to find:
- Artifacts with no edges (isolated nodes — often orphaned specs or stale rules)
- L1 nodes that are unexpectedly large (token cost risk)
- Missing
enforcesedges between hooks and the rules they are meant to enforce - Broken paths or dangling refs reported by
validate_context_graph.py
Distribute. When an agent session starts, load all L1 nodes. For L2 and L3, use the graph edges to identify which artifacts are reachable from the current task context and load only those.
Observe. Each node records last_modified_at from the file system at scan time. The scanner initializes stale: false; freshness is maintained by regenerating the graph after structural changes and validating it in CI or pre-commit.
---
Context Impact Analysis
When an artifact changes, use graph edges to determine which other artifacts are affected before reloading context.
Changed rule node — backward traversal:
1. Find the rule node in the graph. 2. Collect all nodes with an edge pointing to it (references, imports, or enforces edges with this node as to). 3. Those dependent nodes may need to be reloaded or reviewed for consistency.
Changed spec — subagent impact:
1. Find the spec node. 2. Walk forward to find any subagent nodes that delegates_to a context that includes the spec, or that references the spec directly. 3. Reload those subagent definitions before the next agent turn.
Changed CLAUDE.md or AGENTS.md (L1 nodes):
Because these are always loaded, any change takes effect on the next turn automatically. However, if other artifacts references them, check whether those references are still valid after the change.
Impact analysis replaces the default behavior of reloading all context on any change. On large repositories with many artifacts, targeted reloading reduces token usage and avoids accidental context pollution from unrelated artifacts.
---
Maturity Model Integration
The context graph is a gating requirement for L2 and above in the repository context maturity model (see maturity-model.md):
| Level | Name | Graph requirement |
|---|---|---|
| L0 | No Context | No graph. No documented context artifacts. |
| L1 | Basic Context | Has AGENTS.md or CLAUDE.md. No graph required. |
| L2 | Structured Context | context-graph.json present with at least agents_md or claude_md + at least one rule node. |
| L3 | Automated Context | Full graph: plans, specs, subagents, and documented edges between them. Graph passes validate_context_graph.py and hook-to-rule links are reviewed. |
| L4 | Full Context Engineering | Automated refresh: scan_context_artifacts.py and validate_context_graph.py run in CI or on git commit hook. |
To reach L4, add the scanner to a pre-commit hook or CI step:
# .git/hooks/pre-commit or CI step
python3 /path/to/scan_context_artifacts.py $(git rev-parse --show-toplevel)
python3 /path/to/validate_context_graph.py $(git rev-parse --show-toplevel)/context-graph.json --repo $(git rev-parse --show-toplevel)
git add context-graph.jsonThis ensures context-graph.json is always current when code is committed, and that agents in CI environments start with a fresh graph on every run.
---
Related References
- maturity-model.md — Full 5-level maturity model with scoring checklists
- context-development-lifecycle.md — CDLC phases in depth
- multi-repo-strategy.md — Portfolio-level context graph (dev-context-multi-repo)
- repo-conversion-playbook.md — Step-by-step guide for adding context engineering to an existing repository
Context Resolver Pattern
Source: Adapted from garrytan/gbrain at commit adb02b7826a010700efc968b18df8aaf17d8ffa1. License: MIT. Extracted 2026-04-13.A resolver is a routing table for context. It answers the question "when task type X appears, which document should the agent load first?" Skills say HOW to do something; resolvers say WHAT to load WHEN.
Why Resolvers Matter
The temptation, when an agent gets something wrong, is to put more text into always-on context. Add a caveat to AGENTS.md. Add another rule file. Bolt on an extra section explaining the edge case. Repeat for six months and the hot instruction layer becomes a 20,000-line swamp that the model starts ignoring because attention degrades with length.
The resolver pattern fixes this by separating two things:
- Execution policy (hot layer): the small set of rules that must be true on every request.
- Contextual triggers (resolver layer): pointers that say "when the user asks about X, load document Y first."
The hot layer stays small. The body of knowledge that the model actually needs for any specific task stays out of the prompt until the resolver pulls it in.
How Claude Code Already Does This
Claude Code ships with a built-in resolver: every skill has a description field, and the runtime matches user intent against those descriptions automatically. You don't have to remember /ship exists — the description is the resolver. The same mechanism applies to subagents and hooks.
This is why a terse, specific skill description matters more than a long one. The description is the selector. If the description doesn't distinguish your skill from a neighbor, the resolver can't route to it.
Designing a Resolver Layer for Your Repo
Three rules keep the resolver healthy:
1. One task type → one primary document. When a user asks about deployments, the resolver should point at one deployment doc, not three. If three exist, consolidate or disambiguate. 2. Descriptions carry the trigger vocabulary. The words that appear in user requests should appear in the description. "Run the migration safely under load" → description contains "migration", "safe", "load", not "alters table schema." 3. Leave deep content out of the resolver file. The resolver is a map, not the territory. A ten-line pointer file that says "when the question is about payments, read docs/payments/overview.md + docs/payments/webhooks.md" is more useful than copying the content into the hot layer.
Anti-Pattern: The 20,000-Line AGENTS.md
From the source essay: "A confession: my CLAUDE.md was 20,000 lines. Every single thing I ran across went in there. Every quirk, every pattern, every lesson. Completely ridiculous. The model's attention degraded. Claude Code literally told me to cut it back. The fix: about 200 lines. Just pointers to documents. The resolver loads the right one when it matters."
The diagnostic signal is straightforward: if your always-on context file is longer than a single printed page, you are almost certainly paying for it in two ways — slower sessions and lower adherence. Cut to pointers, move the body into skills or docs, and let description-matched routing handle loading.
Skills vs Resolvers vs Rules
| Layer | Answers | Example |
|---|---|---|
| Skill | How to perform a task | dev-git-workflow/SKILL.md describes branching strategy |
| Resolver | Which document to load when a task type appears | AGENTS.md says "for release steps, read docs/release.md" |
| Rule | What must always be true | .claude/rules/no-force-push-main.md is a hard constraint |
Rules go in the hot layer because they always apply. Resolvers go in the hot layer because they are short pointers. Skills live outside the hot layer and are summoned by the resolver.
Related
- context-development-lifecycle.md — Progressive disclosure pattern and distribution hierarchy (the loading tiers that the resolver targets)
- fast-track-guide.md — When a repo is small enough that a resolver layer is premature
- paradigm-comparison.md — Why rule files and resolver files serve different purposes
Fast-Track Guide
Getting productive with context-driven development quickly. Three tracks based on repo size, plus batch onboarding for organizations with many repos.
Table of Contents
- Key Research Insight (March 2026)
- Quick Wins (Under 5 Minutes Each)
- 30-Minute Fast-Track (Medium Repos, 10K-100K LOC)
- Minute 0-5: Orientation
- Understand the codebase
- Minute 5-15: Create AGENTS.md
- [[Project Name]](#project-name)
- Overview
- Tech Stack
- Commands
- Key Patterns
- Known Constraints
- Conventions
- Minute 15-25: Add 2-3 Rules
- Minute 25-30: First Plan File
- [Use Claude Code to generate: "Create a plan for [your next task]"](#use-claude-code-to-generate-create-a-plan-for-your-next-task)
- 2-Hour Fast-Track (Large Repos, 100K-1M LOC)
- Hour 1: Hierarchical Context
- [[Project Name]](#project-name)
- Overview
- Architecture
- Commands
- Scoped Areas
- Key Decisions
- Cross-Cutting Concerns
- For each major subdirectory
- Rules (5-10 min each)
- Create 3-5 focused rule files covering major concerns
- See agents-memory for templates
- Agents (10-15 min each)
- Create 1-2 specialized subagents for common tasks
- See agents-subagents for templates
- Hour 2: Automation
- Test the setup with a real task
- Use Claude Code to work on something and observe:
- - Does the agent follow your conventions?
- - Are the rules being applied?
- - Is any context missing?
- Common gap: agents don't know about your test patterns
- Fix: add a testing rule or test-writer subagent
- Batch Onboarding (100 Repos)
- Phase 1: Foundation (Week 1)
- Phase 2: Pilot (Week 2-3)
- Phase 3: Scale (Week 4-8)
- Phase 4: Sustain (Ongoing)
- Batch Priority Matrix
- Cross-References
Key Research Insight (March 2026)
Before you start: quality matters more than quantity. ETH Zurich research (arxiv 2602.11988) found that LLM-generated AGENTS.md files actually degrade agent performance by 3% while increasing costs 20%+. Human-written files help only when limited to non-inferable details — things the agent cannot discover by reading your code and docs:
- Custom build/test commands not in package.json or Makefile
- Domain-specific conventions not evident from code patterns
- Known failure modes and workarounds
- Specific CI/CD quirks
Do NOT include: project structure descriptions, dependency lists, or README-level documentation the agent can find itself.
Quick Wins (Under 5 Minutes Each)
Do these first regardless of repo size:
| # | Action | Time | Impact |
|---|---|---|---|
| 1 | Create AGENTS.md with only non-inferable details | 2 min | Portable baseline for agent instructions |
| 2 | Add Claude compatibility only if needed | 2 min | CLAUDE.md wrapper/import or symlink for Claude Code |
| 3 | Add build/test/lint commands to AGENTS.md | 2 min | Agents can verify their own work |
| 4 | Add .claude/rules/ with one coding standard | 3 min | Consistent code style from agents |
| 5 | Add 2-3 repo-specific constraints or failure modes | 3 min | Higher signal than directory summaries |
| 6 | Create docs/ directory | 30 sec | Home for specs and plans |
| 7 | Add .gitignore entries for agent temp files | 1 min | Clean repo state |
| 8 | Set up signed commits: git config commit.gpgsign true | 1 min | Audit trail (required for regulated) |
| 9 | Add PR template with AI disclosure section | 3 min | Transparency in PRs |
| 10 | Run orientation: `wc -l */.{ts,py,go} \ | tail -1` | 30 sec |
30-Minute Fast-Track (Medium Repos, 10K-100K LOC)
For repos where a single developer can understand the whole codebase.
Minute 0-5: Orientation
# Understand the codebase
find . -name '*.ts' -o -name '*.py' -o -name '*.go' | head -20
wc -l $(find . -name '*.ts' -o -name '*.py' -o -name '*.go') | tail -1
cat package.json 2>/dev/null || cat pyproject.toml 2>/dev/null || cat go.mod 2>/dev/null
ls -laMinute 5-15: Create AGENTS.md
# [Project Name]
## Overview
[1-2 sentence description from README]
## Tech Stack
- Language: [e.g., TypeScript 5.x]
- Framework: [e.g., Next.js 15]
- Database: [e.g., PostgreSQL via Prisma]
- Testing: [e.g., Vitest + Playwright]
## Commands
- Build: `npm run build`
- Test: `npm test`
- Lint: `npm run lint`
- Dev: `npm run dev`
## Key Patterns
- [Pattern 1: e.g., "All API routes use middleware chain in src/middleware/"]
- [Pattern 2: e.g., "Database queries go through repository pattern in src/repos/"]
## Known Constraints
- [Constraint 1: e.g., "Use pnpm only; npm lockfiles are rejected in CI"]
- [Constraint 2: e.g., "Playwright tests require local auth seed before running"]
## Conventions
- Commits: conventional commits (feat:, fix:, chore:)
- Branches: feature/*, fix/*, chore/*
- PRs: require 1 approval minimumIf your team uses Claude Code, add CLAUDE.md as either:
@AGENTS.mdor a symlink if that is your team convention.
Minute 15-25: Add 2-3 Rules
mkdir -p .claude/rulesCreate focused rule files (one concern per file):
`.claude/rules/code-style.md` — Key patterns, naming conventions, import ordering
`.claude/rules/testing.md` — Test file location, naming, coverage expectations
`.claude/rules/architecture.md` — Layer boundaries, dependency direction, prohibited patterns
Minute 25-30: First Plan File
Create docs/plans/ and write a small plan for your next task using dev-workflow-planning. This validates the entire setup.
mkdir -p docs/plans
# Use Claude Code to generate: "Create a plan for [your next task]"Result: L1-L2 maturity in 30 minutes. Agents now produce consistent, context-aware output.
2-Hour Fast-Track (Large Repos, 100K-1M LOC)
For repos too large for a single developer to hold in memory.
Hour 1: Hierarchical Context
Step 1 (15 min): Root AGENTS.md
Keep the root file as an orientation guide. Don't try to document everything:
# [Project Name]
## Overview
[Brief description]
## Architecture
[High-level architecture: services, layers, data flow]
## Commands
[Build, test, lint, deploy — the essentials]
## Scoped Areas
- `src/auth/` — Authentication rules live in `src/auth/AGENTS.md`
- `src/payments/` — Payment rules live in `src/payments/AGENTS.md`
- `src/api/` — API layer with shared request/response patterns
- `src/shared/` — Shared utilities
- `packages/` — Internal packages
## Key Decisions
- [Decision 1: e.g., "Event-driven architecture using RabbitMQ"]
- [Decision 2: e.g., "Domain-Driven Design with bounded contexts"]
## Cross-Cutting Concerns
- Error handling: [pattern]
- Logging: [pattern]
- Authentication: [pattern]Step 2 (15 min): Subdirectory AGENTS.md files
For complex subdirectories, create focused context:
# For each major subdirectory
echo "# Auth Module\n\n## Purpose\n...\n## Patterns\n...\n## Testing\n..." > src/auth/AGENTS.md
echo "# Payments Module\n\n## Purpose\n...\n## Patterns\n...\n## Testing\n..." > src/payments/AGENTS.mdStep 3 (30 min): Rules and agents
mkdir -p .claude/rules .claude/agents
# Rules (5-10 min each)
# Create 3-5 focused rule files covering major concerns
# See agents-memory for templates
# Agents (10-15 min each)
# Create 1-2 specialized subagents for common tasks
# See agents-subagents for templatesHour 2: Automation
Step 4 (20 min): Hooks
Set up hooks for the most common pain points. See agents-hooks for patterns:
- Pre-commit: lint check, test runner
- Notification: context reminders
Step 5 (20 min): CI/CD gates
Add compliance gates if regulated. See assets/fca-compliance-gate.yml.
Step 6 (20 min): Validate and iterate
# Test the setup with a real task
# Use Claude Code to work on something and observe:
# - Does the agent follow your conventions?
# - Are the rules being applied?
# - Is any context missing?
# Common gap: agents don't know about your test patterns
# Fix: add a testing rule or test-writer subagentResult: L2-L3 maturity in 2 hours. Agents work within guardrails with automated enforcement.
Batch Onboarding (100 Repos)
Rolling out context-driven development across an organization.
Phase 1: Foundation (Week 1)
1. Create coordination repo (see multi-repo-strategy.md) 2. Create template AGENTS.md with org-wide sections 3. Create mandatory rules (compliance, data handling, AI governance) 4. Write sync scripts for rule distribution
Phase 2: Pilot (Week 2-3)
1. Select 10 pilot repos — pick diverse sizes and tech stacks 2. Priority ordering: Start with most-active repos (highest commit frequency) 3. Apply 30-minute or 2-hour fast-track to each pilot repo 4. Collect feedback: What worked? What context was missing?
Phase 3: Scale (Week 4-8)
1. Batch apply to remaining repos in groups of 10-20 2. Use automation: Template sync or CI/CD sync for mandatory rules 3. Allow local customization: Repo teams own their AGENTS.md content 4. Track maturity: Use audit script from maturity-model.md
Phase 4: Sustain (Ongoing)
1. Monthly context retrospective per team 2. Quarterly org-wide context audit 3. Context curation guild reviews shared rules 4. Retire stale context aggressively
Batch Priority Matrix
| Priority | Criteria | Action |
|---|---|---|
| P1 (now) | Active development + customer-facing + regulated | Full fast-track + compliance gates |
| P2 (week 2-3) | Active development + internal | Standard fast-track |
| P3 (week 4-6) | Moderate activity | Basic AGENTS.md + mandatory rules |
| P4 (later) | Dormant/archived | Minimal AGENTS.md only |
Performance Budgets for the Hot Layer
<!-- Source: github.com/MemPalace/mempalace@6614b9b4e71e67da2236493b036b7bf42ba2d55f (MIT), extracted 2026-04-13 -->
Qualitative guidance like "keep it fast" doesn't survive a sprint. Pin numeric thresholds so CI can enforce them and so tradeoffs become visible at review time:
| Operation | Budget | Why |
|---|---|---|
| Session startup injection (loading L0+L1) | < 100ms | Anything slower is felt as lag on the first token |
| Pre-session hook (e.g. context assembly, environment checks) | < 500ms | Longer hooks push the user past the "it's ready" threshold and erode trust in automation |
| Post-response hook (background save, index write, cron trigger) | < 500ms | Must run out-of-band; user should never wait for it |
| Bookkeeping chat tokens (status messages, "saving…", "indexing…") | Zero | Background work should be invisible; every visible bookkeeping message is a tax on the real work |
Enforcement:
- Put a stopwatch in your hooks. Fail CI or log a warning when a hook exceeds its budget.
- Audit the always-on context monthly. If L0+L1 together cross ~1,000 tokens, the budget is being breached silently on every request.
- When something is slow, move it to the background (async, scheduled, post-response) rather than optimizing the hot path. "Background everything" is cheaper than "make the hot path twice as fast."
Why zero bookkeeping tokens: every "saving context now…" message costs tokens and user attention. Move the save to a PreCompact/Stop hook that runs after the response completes. The user sees the reply; the save runs invisibly. This pattern alone can cut per-session cost meaningfully when bookkeeping previously happened in the chat window.
Cross-References
- agents-memory — Detailed AGENTS.md writing patterns
- agents-memory/references/large-codebase-strategy.md — 100K-1M LOC specific strategies
- docs-ai-prd/references/architecture-extraction.md — Extracting architecture from existing code
- docs-ai-prd/references/convention-mining.md — Mining conventions from codebases
- maturity-model.md — Self-assessment before and after onboarding
- multi-repo-strategy.md — Coordination patterns for batch onboarding
Context-Engineering Framework Selection Matrix (April 2026)
How to pick between the major context-engineering frameworks active in April 2026 — and how they stack without fighting each other.
Table of Contents
- The four-layer model
- Decision matrix — pick by symptom
- Layering matrix — what each replaces vs extends
- Stack recipes
- Anti-stacks
- Maturity signals
- Sources
The four-layer model
The April 2026 landscape resolves cleanly into four layers. A team chooses one answer per layer; conflicts within a layer cause drift, but layers stack cleanly.
| Layer | Role | What it produces |
|---|---|---|
| L0 portable baseline | Cross-tool conventions every agent reads | A single Markdown file at the repo root that all agents pick up natively |
| L1 runtime-specific | Tool-specific extensions for a single CLI/IDE | Per-tool config: .claude/rules/, .codex/agents/, .cursor/rules/, .github/copilot-instructions.md, .clinerules/ |
| L2 capability / methodology | On-demand capabilities or enforced workflow discipline | Skills, plugins, hooks — load conditionally and gate behavior |
| L3 artifact pipeline | Spec → plan → tasks → code as committed artifacts | A specs/ or changes/ directory with structured documents |
L0 is mandatory. L1 is mandatory if a tool refuses to read AGENTS.md. L2 is optional, useful when discipline drift or context rot is the bottleneck. L3 is optional, useful when feature ambiguity is the bottleneck.
Decision matrix — pick by symptom
Read the left column as "the thing my team is currently failing at." Pick exactly one framework per row.
| Symptom | Pick | Why this and not the others |
|---|---|---|
| Conventions drift across Codex / Claude Code / Cursor | AGENTS.md | The only L0 artifact all major tools read natively as of April 2026; LF-stewarded |
| Agent ignores TDD, debugs sloppily, skips brainstorming | superpowers | Skills enforce discipline at runtime (refuse-to-code-until-clarified); AGENTS.md is passive |
| Long sessions degrade — context rot, agent forgets earlier decisions | GSD (get-shit-done) | Built specifically for context rot: fresh subagent dispatch + PROJECT.md / ROADMAP.md / STATE.md planning artifacts |
| Feature ambiguity causes drift; specs and code drift apart | GitHub Spec Kit | Spec → plan → tasks → code artifact pipeline; .specify/specs/<feature>/; most-cited and GitHub-backed |
| Same need as Spec Kit but want lighter / npm-native + ADRs co-located | OpenSpec (Fission-AI) | openspec/changes/, npm install, integrates ADRs alongside specs |
| Repeated domain expertise (PDF / Excel / internal DSL) bloats AGENTS.md | Claude Code Skills | Progressive disclosure: ~100-token metadata always-on, instructions on trigger, scripts on demand |
| GitHub Copilot users need persistent project rules | `.github/copilot-instructions.md` | Only instruction layer Copilot reads natively; path-scoped via .instructions.md with applyTo |
| Cursor IDE users need scoped rules per file/dir | *`.cursor/rules/.mdc`** | YAML frontmatter activation; legacy .cursorrules deprecated |
| Cline (VS Code) workflows | `.clinerules/` | Toggle UI per rule; rules-bank pattern |
| Aider pair-programming sessions | `CONVENTIONS.md` | Loaded every session via .aider.conf.yml |
Layering matrix — what each replaces vs extends
| Framework | Layer | Repo location | Composes with AGENTS.md | Install path |
|---|---|---|---|---|
| AGENTS.md | L0 | /AGENTS.md (+ subdir overlays) | — is the baseline | File only |
| CLAUDE.md / `.claude/rules/` | L1 | /CLAUDE.md, .claude/rules/*.md | Extends (Claude-only behavior) | File only |
| *`.codex/agents/.toml`** | L1 | .codex/agents/ | Extends (Codex parallel workers) | File only |
| *`.cursor/rules/.mdc`** | L1 | .cursor/rules/ | Parallel — Cursor does not read AGENTS.md | File only |
| `.github/copilot-instructions.md` | L1 | .github/ | Parallel — Copilot does not read AGENTS.md | File only |
| `.clinerules/` | L1 | /.clinerules/ | Parallel | File only |
| CONVENTIONS.md (Aider) | L1 | configurable | Parallel | Config flag |
| Claude Code Skills | L2 | ~/.claude/skills/ or .claude/skills/ | Extends (on-demand, doesn't bloat hot layer) | Plugin or filesystem |
| superpowers (obra/superpowers) | L2 | .claude/, .cursor/, .opencode, etc. | Extends (multi-runtime via plugin configs) | Anthropic plugin marketplace |
| GSD (gsd-build/get-shit-done) | L2 | ~/.claude/ or ./.claude/ | Extends (skills + subagents + git hooks) | npx get-shit-done-cc@latest |
| GitHub Spec Kit | L3 | .specify/specs/<feature>/ | Orthogonal — produces docs that feed any agent | uv tool install specify-cli |
| OpenSpec (Fission-AI) | L3 | openspec/changes/ | Orthogonal | npm i -g @fission-ai/openspec |
Stack recipes
| Team profile | Recommended stack |
|---|---|
| Solo dev, single repo, single tool | AGENTS.md only. Add Spec Kit if features ship with ambiguity. |
| Solo dev, Claude Code primary | AGENTS.md + Claude Code Skills (on-demand) + superpowers if drift recurs |
| Small team, mixed tools (Claude + Codex + Cursor) | AGENTS.md (baseline) + thin runtime layers + Spec Kit for feature work |
| Long-running project / monorepo / multi-phase | AGENTS.md + GSD (context-rot is the bottleneck) + Spec Kit for new features |
| Regulated / enterprise (audit, separation of duties) | AGENTS.md + .claude/rules/ + Spec Kit (auditable artifacts) + governance gates from this skill's assets/ directory |
| Cursor-primary IDE shop | .cursor/rules/*.mdc + AGENTS.md mirror + Spec Kit |
| GitHub Copilot shop | .github/copilot-instructions.md + AGENTS.md mirror + Spec Kit |
Anti-stacks
Combinations that fight each other and should not be deployed together without explicit scoping.
| Don't | Reason | Mitigation if you must |
|---|---|---|
| superpowers + GSD without scoping | Both ship skills/subagents — overlap on planning, debugging | Namespace via /sp: vs /gsd: slash prefixes; pick a dominant one for each workflow |
| Spec Kit + OpenSpec on the same repo | Two competing spec stores; agents won't know which is canonical | Pick one; if migrating, archive the other under .archive/ |
Conventions duplicated in AGENTS.md + .cursor/rules + .clinerules + copilot-instructions.md | Drift inevitable across four parallel files | Write once in AGENTS.md or docs/; tool-specific layers reference, never duplicate |
| Claude Code Skills used for always-on policy | Defeats progressive disclosure — that policy belongs in AGENTS.md / .claude/rules/ | Move always-on rules to L0/L1; keep skills for capability that should load conditionally |
| Hot AGENTS.md carrying methodology enforcement (TDD, debugging discipline) | Passive text doesn't enforce; just bloats the hot layer | Move enforcement to L2 (superpowers or custom skills) |
Maturity signals
April 2026 snapshot of adoption signals. Stars and adoption are noisy — use as a sanity check, not as a buy decision.
| Framework | Adoption signal | Backing |
|---|---|---|
| AGENTS.md | 67% of active repos contain CLAUDE.md / AGENTS.md / equivalent (Greptile State of AI Coding 2025) | Linux Foundation (Agentic AI Foundation) |
| GitHub Spec Kit | ~92k stars; v0.8.4 May 2026; 30+ supported agents | GitHub official |
| superpowers (obra/superpowers) | ~150–175k stars; v5.0.7 March 2026; 14 documented skills | Anthropic plugin marketplace listed |
| GSD (gsd-build/get-shit-done) | ~59k stars; v1.39.0; 59 skills + 33 subagents in full mode | Independent (gsd-build org) |
| Claude Code Skills | Official Anthropic product; reference catalog at anthropics/skills | Anthropic |
| OpenSpec (Fission-AI) | Smaller but actively maintained; integrates ADRs; npm package | Fission-AI community |
Cursor rules .cursor/rules/*.mdc | Standardized 2025; widely adopted | Cursor (commercial) |
| Copilot instructions | GA; path-specific instructions added July 2025; agent-specific November 2025 | GitHub official |
| Cline rules | Stable feature; v3.13 toggle UI 2025 | Cline (open source) |
| Aider conventions | Mature, documented behavior change in code output | Aider (open source) |
Sources
External source mapping for this matrix lives in data/sources.json under the entries: agents.md spec, GitHub spec-kit, obra/superpowers, gsd-build/get-shit-done, Fission-AI/OpenSpec, Anthropic Agent Skills overview, cursor.com/docs/rules, Cline rules docs, Aider conventions docs.
Use the maturity-signal numbers in this file as a snapshot, not a tracking signal — re-verify before any procurement or migration decision. Star counts and skill counts move month-to-month; the layer model and the decision matrix are the durable parts of this reference.
Information Routing Rules
Source: Adapted from garrytan/gbrain at commit adb02b7826a010700efc968b18df8aaf17d8ffa1. License: MIT. Extracted 2026-04-13.When new information enters the session — something the user says, something an agent discovers, a decision made in conversation — it belongs in exactly one layer. Get the routing wrong and three failure modes appear: things get re-asked (because the answer lived in the wrong layer), things are lost on reset (because durable knowledge was saved only to session memory), or the hot layer bloats (because everything ends up in AGENTS.md).
The Three Layers and Their Purposes
| Layer | What it stores | Survives agent reset? | Cost to read |
|---|---|---|---|
| Compiled knowledge (docs hub, brain, wiki) | World facts: people, systems, decisions, concepts, architecture | Yes | One retrieval hop |
| Agent memory (operational state) | How the agent should behave: preferences, tool configs, defaults | Depends on platform | In always-on context |
| Session context (conversation window) | What was just said, current task, immediate state | No — ephemeral | Free |
The Boundary Test
For any new piece of information, ask: "Is this about the world, or about how to operate?"
- World → compiled knowledge layer. Facts about entities that are external to the agent and would matter even if you swapped the agent for a different one.
- Operations → agent memory. Guidance that changes how the agent behaves but isn't a fact about anything outside the agent.
- Current conversation → session. What's already in the window. No storage action needed.
Worked Examples
| New information | Layer | Why |
|---|---|---|
| "Pedro is CEO of Acme Corp" | Compiled knowledge | World fact — still true if you swap the agent |
| "Acme raised Series D at $1.2B in March" | Compiled knowledge | World fact — dateable, citable |
| "User prefers concise formatting with no preamble" | Agent memory | Operational — how to respond, not a fact about the world |
| "Always run the lint check before committing" | Agent memory | Operational — enforces behavior, doesn't describe reality |
| "The file I just pasted" | Session | Ephemeral — already in the window |
| "User's take on the zero-to-one framework" | Compiled knowledge | The user's original thinking is world content worth preserving — goes in an originals/ area, not memory |
"API key for Stripe goes in .env" | Agent memory | Operational — a rule for the agent, not a fact about Stripe |
The Three Failure Modes
1. People in agent memory: "Pedro prefers email over Slack" feels like a preference, but it is a fact about Pedro. If you store it in agent memory and the memory wipes on reset, you've lost knowledge that should survive forever. Put it on Pedro's page in the compiled layer. 2. Preferences in the compiled layer: "User likes bullet points over paragraphs" is about agent behavior, not about the world. Parking it in the docs hub clutters pages that should be about entities and decisions. Put it in agent memory. 3. Durable facts in session only: "We decided to use PostgreSQL" said in a single conversation and never written down is lost the moment the window rolls. If it's a decision that will matter next week, write it to the compiled layer in the same turn it gets made.
Lookup Routing
Reading follows the same rule with a safety net: always check the compiled knowledge layer before reaching for an external API or the web.
1. Search the compiled layer for the entity or topic. 2. If found: read the relevant page(s). Use that data as the first-pass answer. External sources only fill gaps. 3. If not found: then and only then reach for external lookup.
Quote from the source: "An agent that reaches for the web before checking its own brain is wasting money and giving worse answers."
When to Apply This
- New repo with durable knowledge needs: apply from day one. Set up the compiled layer structure and the boundary test before the first session.
- Existing repo with a bloated `AGENTS.md`: audit each section. For every item, ask "world or operations?" Move world content out to docs, keep operations in the hot layer.
- Multi-agent setup: the compiled layer is the shared ground truth. Agent memory stays per-agent; the compiled layer is portable across agents.
Related
- fast-track-guide.md — Setting up the initial layer structure in a new repo
- multi-repo-strategy.md — How the three layers distribute across repos when knowledge and behavior have different portability requirements
- context-resolver-pattern.md — The routing layer that connects "user asks X" to "load compiled-layer document Y"
Multi-Repo Context Strategy
Managing context-driven development across 100+ repositories. Patterns for sharing context, enforcing standards, and coordinating AI agent instructions at scale.
flowchart TD
AGENTS["AGENTS.md\n(source of truth)"]
CLAUDE["CLAUDE.md\n(optional wrapper)"]
AGENTS ---|"import or symlink"| CLAUDE
CC["Claude Code\nreads CLAUDE.md"]
CX["Codex\nreads AGENTS.md"]
CLAUDE --> CC
AGENTS --> CX
style AGENTS fill:#d4edda,color:#155724
style CLAUDE fill:#d6eaf8,color:#1b4f72
style CC fill:#e8daef,color:#4a235a
style CX fill:#fdebd0,color:#7e5109Table of Contents
- Cross-Platform Convention
- Coordination Patterns
- Pattern 1: Root Coordination Layer (Recommended for Polyrepo)
- Pattern 2: Template Repository + Sync
- .github/workflows/template-sync.yml
- Pattern 3: Workspace-Level Context
- Developer workflow
- Or via shell alias
- Pattern 4: Centralized MCP Toolshed (from Stripe)
- GitHub Agents and Enterprise Controls (March 2026)
- VS Code Context Engineering Patterns
- Shared vs Local Context
- Mandatory Context (All 100 repos)
- Recommended Context (Most repos)
- Local-Only Context (Per-repo)
- Distribution Mechanisms
- Recommended combination for regulated orgs
- Token Budget at Scale
- Optimization strategies
- Cost estimation (100 repos, 20 developers)
- Sync Scripts
- Validate all repos for compliance
- validate-repos.sh — Run from parent directory containing all repos
- Push mandatory rules to all repos
- sync-rules.sh — Push mandatory rules from coordination repo to all repos
- InnerSource Governance
- Context Curation Guild
- Change Management
- Quarterly Context Audit
- Skill Usage Metrics
- Anti-Patterns
- Related References
Cross-Platform Convention
AGENTS.md is the portable baseline. Add runtime-specific files only when they unlock real capability:
- Codex uses
AGENTS.mddirectly. - Claude Code can use
CLAUDE.md, imports,.claude/rules/, and.claude/agents/. - GitHub Copilot and VS Code can use
AGENTS.md,.github/copilot-instructions.md,.github/instructions/*.instructions.md, and.github/agents/*.agent.md.
If you maintain both AGENTS.md and CLAUDE.md, use a thin wrapper/import or a symlink. The key rule is no duplicated drift.
Coordination Patterns
Choose one primary coordination pattern based on your organization's structure.
Pattern 1: Root Coordination Layer (Recommended for Polyrepo)
A dedicated meta-repo holds shared context. Individual repos maintain focused local context.
coordination-repo/ # Shared context (ONE repo)
├── AGENTS.md # Org-wide agent instructions (PRIMARY)
├── CLAUDE.md # Optional Claude wrapper/import
├── .claude/
│ ├── skills/ -> shared-skills/ # Shared skills (symlink or submodule)
│ ├── rules/
│ │ ├── coding-standards.md # Org-wide coding conventions
│ │ ├── compliance-fca-emi.md # FCA/EMI regulatory rules (mandatory)
│ │ ├── data-handling-gdpr-pci.md # GDPR/PCI DSS rules (mandatory)
│ │ ├── security-baseline.md # Security standards (mandatory)
│ │ └── ai-agent-governance.md # AI tool restrictions (mandatory)
│ └── settings.json
├── .github/
│ ├── copilot-instructions.md # GitHub-wide agent guidance
│ ├── instructions/ # Path-specific instructions
│ └── agents/ # Custom GitHub/Copilot agents
├── docs/
│ ├── architecture-overview.md # Cross-repo architecture map
│ └── engineering-standards.md # Org-wide engineering standards
├── templates/
│ ├── AGENTS.md.template # Starting point for new repos
│ ├── pr-template.md # PR template with AI disclosure
│ └── compliance-gate.yml # CI/CD workflow template
└── scripts/
├── clone-repos.sh # Onboard new developers
├── sync-rules.sh # Push rule updates to all repos
├── validate-repos.sh # Audit all repos for compliance
└── sync-agent-entrypoints.sh # Keep entrypoints alignedper-repo/ (each of 100 repos)
├── AGENTS.md # Repo-specific context (PRIMARY)
├── CLAUDE.md # Optional Claude wrapper/import
├── .claude/
│ └── rules/ # Repo-specific rules only
│ └── domain-patterns.md # Tech/domain-specific rules
├── .github/
│ ├── copilot-instructions.md # Optional GitHub/Copilot guidance
│ ├── instructions/ # Optional path-specific instructions
│ └── agents/ # Optional custom agents
├── docs/
│ ├── specs/ # Feature specifications
│ └── plans/ # Implementation plans
└── ...How it works: 1. Developer clones coordination repo alongside work repos 2. claude --add-dir ../coordination-repo loads shared context into sessions 3. Shared rules supplement (not replace) repo-local rules 4. Updates to shared rules go through PR review in coordination repo
Pattern 2: Template Repository + Sync
GitHub template repo with .claude/, AGENTS.md, CI workflows. New repos start from template; updates propagated via sync workflow.
# .github/workflows/template-sync.yml
name: Sync from template
on:
schedule:
- cron: '0 6 * * 1' # Weekly Monday 6am
workflow_dispatch:
jobs:
sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Sync mandatory rules
run: |
# Pull latest mandatory rules from template repo
git clone --depth 1 https://github.com/org/template-repo /tmp/template
cp /tmp/template/.claude/rules/compliance-*.md .claude/rules/
cp /tmp/template/.claude/rules/data-handling-*.md .claude/rules/
cp /tmp/template/.claude/rules/ai-agent-governance.md .claude/rules/
# Do NOT overwrite repo-specific AGENTS.md or local rules
- name: Create PR if changes
run: |
if [ -n "$(git status --porcelain)" ]; then
git checkout -b template-sync-$(date +%Y%m%d)
git add .claude/rules/
git commit -m "chore: sync mandatory rules from template"
gh pr create --title "Sync mandatory rules" --body "Automated sync from template repo"
fiBest for: Organizations that want automated propagation without --add-dir.
Pattern 3: Workspace-Level Context
Claude Code --add-dir loads shared context from a coordination repo at session start.
# Developer workflow
claude --add-dir ~/work/coordination-repo --add-dir ~/work/service-repo
# Or via shell alias
alias cc-service='claude --add-dir ~/work/coordination-repo'
cc-service # Start session with shared context pre-loadedBest for: Small organizations (5-20 repos) where a full coordination repo feels heavy.
Pattern 4: Centralized MCP Toolshed (from Stripe)
A single MCP server aggregates 400+ tools spanning internal systems and SaaS platforms. Agents connect to one endpoint and get access to documentation, ticket details, build statuses, code intelligence, and more.
┌─────────────────────────────────────┐
│ Toolshed (MCP Server) │
│ ┌──────────┐ ┌──────────────────┐ │
│ │ Internal │ │ Code Intelligence│ │
│ │ Docs │ │ (Sourcegraph) │ │
│ └──────────┘ └──────────────────┘ │
│ ┌──────────┐ ┌──────────────────┐ │
│ │ Ticket │ │ Build/CI Status │ │
│ │ Systems │ │ │ │
│ └──────────┘ └──────────────────┘ │
└──────────────┬──────────────────────┘
│ MCP protocol
┌──────────┼──────────┐
▼ ▼ ▼
Agent A Agent B Agent C
(Service X) (Service Y) (Service Z)Key patterns from Stripe:
- Pre-hydration: Deterministically run relevant MCP tools on linked resources before agent starts (faster than agent-driven exploration)
- Curated access: Agents get a subset of tools relevant to their task, not all 400+
- Agent rule files: Conditional rules by subdirectory — same formats as Cursor/Claude Code
- Scale result: 1,000+ merged PRs per week across hundreds of millions of LOC
Best for: Large organizations (50+ repos) with centralized platform teams who can maintain the MCP server. Requires investment but provides the richest context.
Combining patterns: Stripe's Toolshed (Pattern 4) complements the Coordination Repo (Pattern 1). Use Pattern 1 for static context (rules, AGENTS.md templates) and Pattern 4 for dynamic context (ticket details, build status, code search).
GitHub Agents and Enterprise Controls (March 2026)
GitHub now provides two complementary layers:
- Repository context surfaces:
AGENTS.md,.github/copilot-instructions.md, and.github/instructions/*.instructions.md - Agent surfaces:
.github/agents/*.agent.mdplus GitHub Copilot coding agent and third-party agents
For enterprise governance, GitHub's agent control plane adds:
- audit-log events that distinguish agent actions from human actions
- session-level visibility for agent tasks
- enterprise controls for which agents and MCP servers are allowed
Use GitHub for platform-level governance and execution. Use the coordination repo for shared policy, templates, and cross-repo standards.
VS Code Context Engineering Patterns
VS Code's March 2026 guidance converges on the same layered model:
1. AGENTS.md as a portable baseline 2. .github/copilot-instructions.md for repo-wide GitHub/Copilot instructions 3. .github/instructions/*.instructions.md for path-specific behavior 4. .github/agents/*.agent.md for planning or implementation personas
For multi-repo organizations, standardize the baseline plus the runtime-specific layers you actually use.
Shared vs Local Context
Mandatory Context (All 100 repos)
These are the baseline artifacts for regulated organizations. AGENTS.md and the compliance rule files are mandatory. CLAUDE.md is optional, but if present it must stay aligned:
| File | Purpose | Enforcement |
|---|---|---|
AGENTS.md | Portable agent instructions | CI check: file exists |
CLAUDE.md | Optional Claude wrapper/import | CI check: if present, no duplicated drift |
.claude/rules/compliance-fca-emi.md | FCA/EMI audit trail, separation of duties | Template sync |
.claude/rules/data-handling-gdpr-pci.md | GDPR/PCI safe/prohibited data | Template sync |
.claude/rules/ai-agent-governance.md | AI tool restrictions, disclosure | Template sync |
Recommended Context (Most repos)
| File | Purpose | When to skip |
|---|---|---|
.claude/rules/coding-standards.md | Code style, patterns | Archived repos |
.claude/rules/commit-conventions.md | Commit message format | Archived repos |
.github/pull_request_template.md | PR template with AI disclosure | Internal-only repos |
Local-Only Context (Per-repo)
| File | Purpose | Examples |
|---|---|---|
| AGENTS.md body | Repo-specific instructions | "This is a Next.js app using Prisma..." |
.claude/rules/domain-*.md | Domain patterns | Payment flows, auth patterns |
.claude/agents/*.md | Specialized subagents | Test writer, migration helper |
docs/architecture.md | Repo architecture | Service boundaries, data flow |
Distribution Mechanisms
| Mechanism | Pros | Cons | Best For |
|---|---|---|---|
| Git submodule | Version-pinned, explicit updates | Requires git submodule update | Strict version control |
| Symlinks | Fast, no extra tooling | Fragile on Windows, path-dependent | Unix-only teams |
| NPM/package | Semver, familiar tooling | Overhead for non-JS repos | JS/TS monorepos |
| CI/CD sync | Automated, auditable | PR noise, delayed propagation | Regulated environments |
| `--add-dir` | Zero setup per repo | Requires coordination repo clone | Developer workstations |
| Template sync | Automated PR creation | Requires merging sync PRs | Large orgs with many repos |
Recommended combination for regulated orgs
1. CI/CD sync for mandatory compliance rules (automated, auditable) 2. `--add-dir` for shared skills and coding standards (developer convenience) 3. Template repo for new repo bootstrapping (consistent starting point)
Token Budget at Scale
Context has a cost. Budget it:
| Context Layer | Approximate Tokens | Notes |
|---|---|---|
| Shared rules (mandatory) | ~2,000 | Compliance + data handling + governance |
| Shared rules (recommended) | ~1,500 | Coding standards + commit conventions |
| Repo AGENTS.md | ~500-2,000 | Varies by repo complexity |
| Skills discovery | ~500 | Skill router overhead |
| Workspace overhead | ~4,500-6,000 | Before any task-specific context |
| Available for work | ~144,000-195,000 | Depends on model context window |
Optimization strategies
- Progressive disclosure: Load detailed rules only when relevant (use rule file names as triggers)
- Scoped AGENTS.md: Keep top-level brief, use subdirectory AGENTS.md for deep context
- Sub-agent isolation: Heavy research in subagents (separate context windows)
- RAG patterns: For repos with extensive documentation, summarize in AGENTS.md, link to full docs
Cost estimation (100 repos, 20 developers)
Per session: ~5K tokens overhead + ~50K tokens work = ~55K tokens
Sessions per developer per day: ~10
Daily org total: 20 devs x 10 sessions x 55K = 11M tokens/day
Monthly: ~220M tokens (input) + ~40M tokens (output)Sync Scripts
Validate all repos for compliance
#!/bin/bash
# validate-repos.sh — Run from parent directory containing all repos
MANDATORY_FILES=(
"AGENTS.md"
".claude/rules/compliance-fca-emi.md"
".claude/rules/data-handling-gdpr-pci.md"
".claude/rules/ai-agent-governance.md"
)
pass=0; fail=0; total=0
for repo in */; do
[ ! -d "$repo/.git" ] && continue
total=$((total + 1))
repo_pass=true
for file in "${MANDATORY_FILES[@]}"; do
if [ ! -f "$repo/$file" ]; then
echo "MISSING: $repo$file"
repo_pass=false
fi
done
# Check CLAUDE.md does not drift if present
if [ -f "$repo/CLAUDE.md" ] && [ ! -L "$repo/CLAUDE.md" ] && ! grep -q '@AGENTS.md' "$repo/CLAUDE.md"; then
echo "REVIEW: ${repo}CLAUDE.md exists but is neither a wrapper nor a symlink"
repo_pass=false
fi
if $repo_pass; then
pass=$((pass + 1))
else
fail=$((fail + 1))
fi
done
echo ""
echo "Results: $pass/$total repos compliant ($fail non-compliant)"Push mandatory rules to all repos
#!/bin/bash
# sync-rules.sh — Push mandatory rules from coordination repo to all repos
COORDINATION_REPO="./coordination-repo"
MANDATORY_RULES=(
"compliance-fca-emi.md"
"data-handling-gdpr-pci.md"
"ai-agent-governance.md"
)
for repo in repos/*/; do
[ ! -d "$repo/.git" ] && continue
name=$(basename "$repo")
# Ensure .claude/rules/ exists
mkdir -p "$repo/.claude/rules"
# Copy mandatory rules
for rule in "${MANDATORY_RULES[@]}"; do
cp "$COORDINATION_REPO/.claude/rules/$rule" "$repo/.claude/rules/$rule"
done
# Ensure Claude compatibility wrapper if desired
if [ -f "$repo/AGENTS.md" ] && [ ! -f "$repo/CLAUDE.md" ]; then
printf '@AGENTS.md\n' > "$repo/CLAUDE.md"
fi
echo "Synced: $name"
doneInnerSource Governance
For organizations managing shared context at scale:
Context Curation Guild
- Members: 1 engineering lead per team + security + compliance + platform
- Cadence: Monthly review of shared rules and skills
- Authority: Approve/reject changes to mandatory rules in coordination repo
- CODEOWNERS:
.claude/rules/compliance-*owned by compliance team
Change Management
- Mandatory rules: Require 2 approvals (engineering + compliance)
- Recommended rules: Require 1 approval (engineering lead)
- Local rules: Team discretion (no cross-team review)
- Breaking changes: Announced 2 weeks before propagation, major version bump
Quarterly Context Audit
1. Review context freshness: git log --since="90 days" -- AGENTS.md .claude/ 2. Identify stale rules (no updates in 6+ months with active repo) 3. Measure rule compliance rate across repos 4. Survey developers: "Which rules helped? Which were noise?" 5. Retire low-value rules, update outdated ones
Skill Usage Metrics
- Track which skills are invoked (if instrumented)
- Retire skills with <5% usage over a quarter
- Promote high-usage skills to mandatory/recommended
Anti-Patterns
| Anti-Pattern | Problem | Fix |
|---|---|---|
| God coordination repo | 5000+ line AGENTS.md covering everything | Keep coordination AGENTS.md to org-wide concerns only |
| Copy-paste rules | Same rules duplicated across 100 repos | Use sync mechanism, single source of truth |
| Divergent entrypoints | CLAUDE.md drifts away from AGENTS.md | Enforce wrapper-or-symlink checks in CI |
| Manual sync | "Remember to copy rules when they change" | Automate with CI/CD sync workflow |
| No local context | Repos rely entirely on coordination repo | Each repo needs its own AGENTS.md with repo-specific content |
| Over-syncing | Every rule synced to every repo | Distinguish mandatory (sync) vs recommended (opt-in) |
Durable vs Replaceable — The Tool-Portability Boundary
<!-- Source: github.com/garrytan/gbrain@adb02b7826a010700efc968b18df8aaf17d8ffa1 (MIT), extracted 2026-04-13 -->
The patterns above handle portfolio multi-repo strategy — many services, one org, shared rules. There's a second, orthogonal axis worth naming explicitly: splitting agent behavior from world knowledge into two repos along a durability line.
The boundary test (apply to every file):
| Question | If YES → | Example |
|---|---|---|
| Would this file transfer if you switched AI agents? | Agent repo (replaceable) | AGENTS.md, .claude/rules/, hooks, subagent configs, operational state |
| Would this file transfer if you switched to a different person or team? | Knowledge repo (durable) | Architecture docs, decision records, system maps, domain concepts, entity dossiers |
The two axes — "which agent runs this?" and "whose knowledge is this?" — are independent. A repo can have:
- Replaceable and portable → agent repo
- Durable and org-owned → knowledge/docs repo
- Both → split into two repos so the survival rules are explicit
Why this matters: if agent config and world knowledge live in the same repo, you lose one when you swap the other. Switch from Claude Code to Codex and you shouldn't lose your architecture docs. Change teams and the incoming team shouldn't inherit your personal tool preferences. The split makes each failure mode impossible by construction.
Decision tree for a new file:
About a person, company, system, decision, or domain concept → knowledge repo
About how the agent should behave → agent repo
Original thinking (yours, an architect's, a PM's) → knowledge repo (under an originals/ area)
Session logs, daily ops state, task lists → agent repo
Skill configs, hooks, cron definitions → agent repo
Rules about policy, compliance, safety → knowledge repo if org-wide, agent repo if agent-localInteraction with the portfolio patterns above: the durable/replaceable split happens per organizational unit (a team, a user, a project). The portfolio patterns handle how multiple such units coordinate. Pattern 1 (Root Coordination Layer) can itself be split — the coordination repo holds shared policy (durable), while each developer's agent config lives elsewhere (replaceable).
Related References
- maturity-model.md — Assess readiness before scaling
- regulated-environment-patterns.md — Compliance rules that must be synced
- fast-track-guide.md — Batch onboarding for 100 repos
- context-development-lifecycle.md — The CDLC feedback loop at scale
- information-routing-rules.md — The per-information routing rule (world vs operations vs session) that complements this per-file repo boundary
Regulated Environment Patterns
FCA/EMI compliance patterns for AI-driven development. Covers regulatory framework mapping, mandatory agent rules, CI/CD compliance gates, change approval workflows, and audit trail requirements.
Table of Contents
- Regulatory Framework Coverage
- PS21/3: Operational Resilience
- SS1/23: Model Risk Management
- SM&CR: Senior Managers and Certification Regime
- PS24/16: Critical Third Parties (CTP)
- GDPR / UK GDPR
- PCI DSS
- NIST AI Agent Standards Initiative (2026)
- FINRA 2026: AI Agent Regulatory Precedent
- Industry Evidence: AI Agents in Regulated Fintech
- Stripe Minions (1,000+ PRs/week, $1T+ payment volume)
- Mandatory Agent Rules
- 1. FCA/EMI Compliance (`.claude/rules/compliance-fca-emi.md`)
- 2. Data Handling (`.claude/rules/data-handling-gdpr-pci.md`)
- 3. AI Agent Governance (`.claude/rules/ai-agent-governance.md`)
- Change Approval Workflow
- Standard Flow
- Enhanced Flow (Security-Critical Paths)
- CODEOWNERS Configuration
- .github/CODEOWNERS
- Security-critical directories require security team review
- Agent rules require compliance review
- Infrastructure requires DevOps review
- Audit Trail Requirements
- Git as Compliance Tool
- PR Description Template
- Quarterly Integrity Checks
- Run quarterly across all repos
- Audit Log Export
- Export audit log for a date range
- Compliance-Aware CI/CD
- Gate Summary
- Compliance Metrics
- Incident Response: AI Tool Failures
- Severity Classification
- Post-Incident Actions
- Agent Execution Security
- Sandbox Isolation Patterns
- GitHub Enterprise Agent Audit Integration
- Related References
Regulatory Framework Coverage
PS21/3: Operational Resilience
AI coding tools are critical dependencies in your Important Business Services (IBS):
- Impact tolerance: Define maximum tolerable disruption if AI tools become unavailable
- Scenario testing: Test manual fallback pathways quarterly (can your team ship without AI agents?)
- Dependency mapping: Document AI tool providers (Anthropic, OpenAI) in your IBS dependency register
- Exit strategy: Maintain ability to develop without any single AI provider (dual-agent strategy helps)
SS1/23: Model Risk Management
AI-generated code is model output that must be governed:
- Inventory: Track which code artifacts were AI-generated (PR disclosure, commit metadata)
- Validation: Human review required for all AI-generated code before merge
- Testing: AI-generated code must meet same test coverage thresholds as human code
- Explainability: Developers must understand AI-generated code before approving
- Monitoring: Track defect rates in AI-generated vs human-written code
SM&CR: Senior Managers and Certification Regime
Named accountability for AI tool governance:
- Senior Manager Function: Designate SMF responsible for AI tool governance (typically CTO/CIO)
- Delegation is not a defense: "The AI did it" is not an acceptable explanation to the FCA
- Reasonable steps: Document policies, training, and controls for AI tool usage
- Certification: Developers using AI tools should be certified under SM&CR if in scope
PS24/16: Critical Third Parties (CTP)
AI providers may be designated as Critical Third Parties:
- Portability: Maintain ability to switch between AI providers and context surfaces
- Concentration risk: Do not depend on a single AI provider for all development
- Contractual provisions: Ensure DPA and service terms with AI providers meet FCA requirements
- Incident reporting: AI tool outages affecting IBS must be reported per operational resilience framework
GDPR / UK GDPR
Data protection requirements for AI-assisted development:
- DPA: Data Processing Agreement with Anthropic and OpenAI (both offer DPAs)
- DPIA: Data Protection Impact Assessment if AI processes personal data
- Context safety: Agent context files (AGENTS.md, rules, plans) must NEVER contain personal data
- Lawful basis: Legitimate interest for code generation; explicit consent if processing customer data patterns
- Right to explanation: If AI-generated decisions affect individuals, explainability required
PCI DSS
Payment Card Industry requirements:
- Card data prohibition: Real or synthetic card numbers must NEVER appear in agent context, prompts, or code comments
- Segmentation: AI agents must not have access to cardholder data environments
- Logging: AI tool access to payment-related code must be auditable
- Key management: AI agents must never see encryption keys, even in test environments
NIST AI Agent Standards Initiative (2026)
The first US government framework specifically targeting autonomous AI agents, launched by NIST's Center for AI Standards and Innovation (CAISI):
Three pillars: 1. Industry-led standards: Gap analyses, voluntary guidelines, international standards coordination 2. Community-led protocols: Open-source agent protocol interoperability (NSF investment) 3. Security research: Agent authentication, identity infrastructure, security evaluations
Key focus areas for coding agents:
- Agent identity and authorization: How agents authenticate and what permissions they hold
- Governance and oversight controls: Human supervision, escalation protocols, access controls
- Security controls: Mitigating misuse, privilege escalation, unintended autonomous actions
Relevance for FCA-regulated firms: While NIST standards are US-focused, they provide a complementary framework. FCA-regulated firms operating internationally should track NIST developments for alignment opportunities.
FINRA 2026: AI Agent Regulatory Precedent
FINRA's 2026 Regulatory Oversight Report contains the first dedicated section on AI agents by a major financial regulator, defining them as "systems capable of autonomous actions on behalf of users":
Agent-specific risks identified:
- Autonomy without human validation and approval
- Scope creep beyond intended authority
- Auditability challenges (multi-step reasoning difficult to trace)
- Data sensitivity (unintended storage or disclosure)
- Misaligned reward functions affecting outcomes
Required controls (applicable to coding agents):
- Track and log agent actions and decisions
- Store prompt and output logs for accountability
- Record which model version was used and when
- Implement human-in-the-loop review procedures
- Define guardrails to restrict agent behaviors
Mapping to FCA context: While FINRA is a US regulator, its specificity on AI agent audit trails is more detailed than current FCA guidance. FCA-regulated EMIs should proactively adopt FINRA's logging recommendations as best practice — regulators learn from each other.
Industry Evidence: AI Agents in Regulated Fintech
Stripe Minions (1,000+ PRs/week, $1T+ payment volume)
Stripe's internal coding agents demonstrate that AI-generated code at scale is compatible with stringent financial regulation:
| Control | Stripe's Implementation | FCA Equivalent |
|---|---|---|
| Isolation | Pre-warmed devboxes, no production/internet access | Operational resilience (PS21/3) |
| Human review | All agent output requires human review before merge | Separation of duties (SM&CR) |
| Verification | Max 2 CI rounds, local lint <5s, selective test running | Model risk validation (SS1/23) |
| Context rules | Agent rule files conditional by subdirectory | .claude/rules/ per directory |
| Tool governance | Curated MCP tool subset per task (from 400+) | Approved tool list |
| Audit trail | Full visibility into agent decisions via web UI | PR disclosure + signed commits |
Key takeaway for FCA-regulated EMIs: If Stripe can merge 1,000+ AI-generated PRs weekly while processing $1T+ in payments, the approach is viable for EMIs — but requires the same rigor: isolation, human review, verification constraints, and auditability.
Isolation pattern worth adopting: Stripe's devboxes are fully isolated from production and the internet. For EMIs, consider container-based agent execution environments that:
- Cannot reach production databases or APIs
- Cannot make outbound network calls (prevents data exfiltration)
- Are pre-loaded with code and test infrastructure only
- Spin up in <30 seconds for developer ergonomics
Mandatory Agent Rules
These rules templates must be installed in every repository. Copy from assets/ directory.
1. FCA/EMI Compliance (.claude/rules/compliance-fca-emi.md)
Covers:
- Signed commits required (audit trail)
- No force-push (immutable history)
- Merge commits only to main (traceable changes)
- AI cannot approve or deploy (separation of duties)
- Different reviewer required (four-eyes principle)
- Prohibited: auto-merge to production branches
- Model risk: all AI-generated artifacts tracked
See: assets/compliance-fca-emi.md for copy-ready template.
2. Data Handling (.claude/rules/data-handling-gdpr-pci.md)
Covers:
- Safe data categories (code abstractions, business logic, synthetic test data)
- Prohibited data categories (PII, card data, credentials, connection strings)
- Context filtering patterns
- Test data guidelines
See: assets/data-handling-gdpr-pci.md for copy-ready template.
3. AI Agent Governance (.claude/rules/ai-agent-governance.md)
Covers:
- Approved AI tool list
- Usage restrictions per environment
- Disclosure requirements
- Training requirements
- Incident response for AI tool failures
See: assets/ai-agent-governance.md for copy-ready template.
Change Approval Workflow
sequenceDiagram
participant Dev as Developer + AI Agent
participant PR as Pull Request
participant Rev as Code Reviewer<br/>(different person)
participant CI as CI/CD Gates
participant Sec as Security Reviewer<br/>(if critical path)
participant Ops as DevOps
Dev->>PR: Create PR with AI disclosure
PR->>Rev: Request review
Rev->>PR: Approve (four-eyes)
PR->>CI: Run compliance gates
Note over CI: Signed commits<br/>Secrets scan<br/>SAST<br/>PII detection<br/>AI disclosure check
CI->>PR: All gates pass
alt Security-critical path
PR->>Sec: Request security review
Sec->>PR: Approve
end
PR->>PR: Merge (merge commit, no squash)
PR->>Ops: Request deployment
Ops->>Ops: Deploy (separate approval)Standard Flow
Developer + AI Agent
↓ creates PR
Human Review (PR author cannot be sole reviewer)
↓ approves
Code Reviewer (different person, required)
↓ approves
Automated Gates (CI/CD)
├── Signed commit verification
├── Secrets detection (gitleaks)
├── SAST scanning
├── PII pattern detection
├── AI disclosure check
├── Test coverage threshold
└── Dependency vulnerability scan
↓ all pass
Merge to main (merge commit, no squash)
↓
DevOps approves deployment (separate from code approval)Enhanced Flow (Security-Critical Paths)
For changes touching auth/, payments/, crypto/, compliance/:
Standard Flow
↓ plus
Security Reviewer (separate from code reviewer)
↓ approves
Compliance Check (manual or automated)
↓ clears
Merge with 2+ approvalsCODEOWNERS Configuration
# .github/CODEOWNERS
# Security-critical directories require security team review
/auth/ @org/security-team @org/backend-leads
/payments/ @org/security-team @org/payments-team
/crypto/ @org/security-team
/compliance/ @org/compliance-team @org/security-team
# Agent rules require compliance review
/.claude/rules/compliance-* @org/compliance-team
/.claude/rules/data-handling* @org/compliance-team @org/security-team
# Infrastructure requires DevOps review
/.github/workflows/ @org/devops-team
/terraform/ @org/devops-team
/k8s/ @org/devops-teamAudit Trail Requirements
Git as Compliance Tool
Git provides an immutable, signed audit trail when configured correctly:
| Requirement | Git Implementation | Enforcement |
|---|---|---|
| Immutability | No force-push, no rebase on main | Branch protection rules |
| Attribution | Signed commits (GPG/SSH) | git config commit.gpgsign true |
| Traceability | Merge commits (no squash) | Branch protection: merge commits only |
| Disclosure | PR template with AI involvement | PR template check in CI |
| Chronology | Commit timestamps | Git's native ordering |
| Integrity | SHA-256 commit hashes | git fsck --full quarterly |
PR Description Template
Every PR must include AI involvement disclosure. See assets/pr-template-ai-disclosure.md.
Key fields:
- AI tools used (Claude Code, Codex, Cursor, Copilot, none)
- AI role (generated code, reviewed code, generated tests, assisted debugging)
- Human verification checklist (understood code, ran tests, reviewed security, checked compliance)
- Files primarily AI-generated (list)
- Confidence level (high/medium/low for each AI-generated section)
Quarterly Integrity Checks
# Run quarterly across all repos
for repo in repos/*/; do
echo "=== $(basename $repo) ==="
(cd "$repo" && git fsck --full 2>&1 | tail -1)
(cd "$repo" && git log --oneline --no-merges main | wc -l)
echo "---"
doneAudit Log Export
For compliance reporting, export git history to immutable storage:
# Export audit log for a date range
git log --since="2026-01-01" --until="2026-03-31" \
--format='%H|%ai|%an|%ae|%s' \
--show-signature \
> audit-log-2026-Q1.csvCompliance-Aware CI/CD
See assets/fca-compliance-gate.yml for the full GitHub Actions workflow template.
Gate Summary
| Gate | Tool | Blocks Merge | Purpose |
|---|---|---|---|
| Signed commits | git verify-commit | Yes | Audit trail attribution |
| Secrets detection | gitleaks | Yes | Prevent credential exposure |
| SAST scanning | Semgrep/CodeQL | Yes | Vulnerability detection |
| PII detection | Custom regex | Yes | Data protection |
| AI disclosure | PR template check | Yes | Regulatory transparency |
| Test coverage | Coverage tool | Yes (if below threshold) | Code quality |
| Dependency scan | Dependabot/Snyk | Warning | Supply chain security |
| License check | License tool | Warning | Legal compliance |
Compliance Metrics
Track and report these metrics for regulatory purposes:
| Metric | Target | Frequency | Report To |
|---|---|---|---|
| % repos with mandatory rules | 100% | Weekly | CTO/compliance |
| % PRs with AI disclosure | 100% | Weekly | Engineering leads |
| Security scan pass rate | >95% | Daily | Security team |
| Mean time to gate resolution | <4 hours | Weekly | Engineering leads |
| Signed commit compliance | 100% | Daily | DevOps |
| Force-push attempts blocked | 0 | Daily | Security team |
| PII detection true positive rate | >80% | Monthly | DPO |
| Quarterly git integrity pass | 100% | Quarterly | Compliance/audit |
Incident Response: AI Tool Failures
When an AI tool fails or produces problematic output:
Severity Classification
| Severity | Criteria | Response Time | Escalation |
|---|---|---|---|
| P1 Critical | AI-generated code causes production incident | 15 min | CTO + compliance |
| P2 High | AI tool leaks sensitive data | 1 hour | Security + DPO |
| P3 Medium | AI tool produces non-compliant code (caught in review) | 24 hours | Engineering lead |
| P4 Low | AI tool unavailable | 48 hours | DevOps |
Post-Incident Actions
1. Isolate: Revert AI-generated code if in production 2. Investigate: Determine root cause (context issue, model behavior, human oversight failure) 3. Remediate: Fix the immediate issue 4. Prevent: Update rules, gates, or training to prevent recurrence 5. Report: Log incident per operational resilience framework
Agent Execution Security
Sandbox Isolation Patterns
For regulated environments, agent code execution requires isolation beyond git worktrees. Choose isolation level based on threat model:
| Technology | Isolation | Boot Time | Security Level | Best For |
|---|---|---|---|---|
| Git worktrees | Branch-level | Instant | Code isolation only | Development (L2) |
| Docker containers | Process (shared kernel) | Milliseconds | Process-level | Trusted, audited code |
| gVisor | Syscall interception | Milliseconds | Syscall-level | CI/CD, multi-tenant |
| Firecracker microVM | Hardware (dedicated kernel) | ~125ms | Hardware-enforced | Production agents, regulated |
| Kata Containers | Hardware (via VMM) | ~200ms | Hardware-enforced | Kubernetes, regulated industries |
Recommendation for FCA-regulated EMIs:
- Development: Git worktrees (standard for agent isolation)
- CI/CD: gVisor or Firecracker (stronger isolation for automated runs)
- Production agent execution: Firecracker microVMs (dedicated kernel, <5 MiB overhead)
Defense-in-depth for agent execution: 1. Network isolation: Block all outbound connections by default; whitelist only required endpoints 2. Resource limits: CPU/memory caps, disk quotas, I/O rate limiting 3. Zero-trust credentials: Short-lived tokens with task-specific scope 4. Human-in-the-loop gates: Approval required for high-risk operations 5. Immutable audit trails: Track every code execution, tool call, and API request
Sandboxing and network restriction materially reduce blast radius compared to unrestricted agent execution.
GitHub Enterprise Agent Audit Integration
GitHub's enterprise agent controls provide platform-level audit capabilities that complement repository-level compliance:
Audit log enhancements for agents:
- agent-specific audit events distinguish agent actions from human actions
- session-level task events capture lifecycle and status
- events can be reviewed at organization and enterprise scope
Enterprise governance features:
- custom agent definitions in
.github/agents/ - enterprise controls for approved agents and MCP servers
- policy enforcement and review at org / enterprise scope
- custom roles for AI governance
Integration with FCA compliance: These controls map to FCA requirements:
- agent-specific audit events → SM&CR accountability
- session events → PS21/3 operational resilience
- approved-agent and MCP controls → PS24/16 third-party governance
- protected agent definition files → separation of duties
Related References
- multi-repo-strategy.md — How to distribute compliance rules across repos
- maturity-model.md — L3+ requires compliance gates
- context-development-lifecycle.md — Compliance rules need CDLC maintenance
- software-security-appsec — Application security patterns (OWASP, auth)
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/dev-context-engineering/schemas/context-graph.schema.json",
"title": "ContextGraph",
"description": "Per-repo context graph: instructions, rules, specs, plans, hooks, subagents, references, assets, and the relationships between them.",
"type": "object",
"required": ["meta", "nodes", "edges"],
"properties": {
"meta": {
"type": "object",
"required": ["scope", "generated_at"],
"properties": {
"scope": { "type": "string" },
"generated_at": { "type": "string", "format": "date-time" },
"graph_contract_version": {
"type": "string",
"description": "Schema contract version. Bump on breaking changes."
},
"maturity_level": { "type": "string", "enum": ["L0","L1","L2","L3","L4"] },
"validation": {
"type": "object",
"properties": {
"checks_passed": { "type": "integer" },
"checks_total": { "type": "integer" },
"last_validated_at": { "type": "string", "format": "date-time" }
}
}
}
},
"nodes": {
"type": "array",
"items": {
"type": "object",
"required": ["id", "type", "label", "path"],
"properties": {
"id": { "type": "string" },
"type": {
"type": "string",
"enum": ["agents_md","claude_md","rule","spec","plan","subagent","hook","copilot_instructions","github_agent","reference","asset","skill"]
},
"label": { "type": "string" },
"path": { "type": "string" },
"summary": {
"type": "string",
"description": "1-2 sentence description of this artifact's purpose."
},
"tags": {
"type": "array",
"items": { "type": "string" }
},
"last_modified_at": { "type": "string", "format": "date-time" },
"last_verified_at": { "type": "string", "format": "date-time" },
"first_seen_at": { "type": "string", "format": "date-time" },
"token_cost": { "type": "integer" },
"loading_tier": { "type": "string", "enum": ["L1_always","L2_on_demand","L3_referenced"] },
"stale": { "type": "boolean" },
"confidence": { "type": "number", "minimum": 0, "maximum": 1 },
"evidence": {
"type": "array",
"items": { "type": "object" },
"description": "Provenance refs (file paths, line ranges, scan timestamps). LLM-enrichable."
},
"importance": {
"type": "number",
"minimum": 0,
"description": "Fan-in count or PageRank score. Computed by validate/query passes."
}
}
}
},
"edges": {
"type": "array",
"items": {
"type": "object",
"required": ["source", "target", "relation"],
"properties": {
"source": { "type": "string" },
"target": { "type": "string" },
"relation": {
"type": "string",
"enum": ["imports","delegates_to","enforces","documents","triggers","validates","overrides","extends","references","supersedes"]
},
"weight": {
"type": "number",
"minimum": 0,
"maximum": 1,
"description": "Static dependency strength. Convention: enforces=1.0, imports=0.9, delegates_to=0.8, documents=0.5, references=0.3"
},
"weight_static": {
"type": "number",
"minimum": 0,
"maximum": 1,
"description": "Original static weight before calibration. Set by calibration passes."
},
"weight_calibrated": {
"type": "number",
"minimum": 0,
"maximum": 1,
"description": "Calibrated weight from multi-source evidence. Set by calibration passes; preferred when present."
},
"confidence": { "type": "number", "minimum": 0, "maximum": 1 },
"evidence": {
"type": "array",
"items": { "type": "object" },
"description": "Provenance refs that justify this edge (file path, line range, regex match, doc anchor)."
},
"notes": { "type": "string" },
"first_seen_at": { "type": "string", "format": "date-time" },
"last_verified_at": { "type": "string", "format": "date-time" },
"stale": { "type": "boolean" },
"valid_at": {
"type": "string",
"format": "date-time",
"description": "Bitemporal: when this relationship became true in the world. Optional."
},
"valid_until": {
"type": "string",
"format": "date-time",
"description": "Bitemporal: when this relationship stopped being true. Optional. Use null for currently-valid edges."
},
"superseded_by": {
"type": "string",
"description": "Edge id that replaced this edge. Used for supersession instead of deletion."
},
"supersedes": {
"type": "string",
"description": "Edge id that this edge replaces. Inverse of superseded_by."
},
"edge_id": {
"type": "string",
"description": "Stable edge identifier. Required when supersession or bitemporal fields are used."
}
}
}
}
}
}