Introducing a new way to review your PRs.

Read the announcement

affaan-m / agentshield

AI agent security scanner. Detect vulnerabilities in agent configurations, MCP servers, and tool permissions. Available as CLI, GitHub Action, ECC plugin, and GitHub App integration. 🛡️

View on GitHub

20 documents · Updated Sep 11, 2026

docs / repository-discovery-and-context

Repository discovery and context

Repository discovery turns a repository into a typed set of agent, harness, and automation files that security analysis can inspect. Source context then tells the analysis whether each file is likely active configuration, optional local material, documentation, or installed plugin content. A built-in vulnerable configuration corpus provides repeatable attack-shaped inputs so rule coverage can be checked as the scanner changes. This page is a child of Static security analysis and connects to the Security rule engine.

Repository scan

The repository scan starts at a target path and finds configuration surfaces that can affect an agent environment. It returns a ScanTarget with the target path, typed file content, and any broken links found in scanned configuration directories. The scanner uses this shared input for static rules and for other checks that need configuration context. References: src/…/discovery.ts• L90-107, src/…/index.ts• L30-45, src/types.ts• L60-84

The scan looks for common root files and nested directories used by several agent tools. It includes instruction files, settings, MCP server definitions, agents, skills, commands, rules, contexts, hook files, package-manager settings, and selected editor or startup surfaces. It also searches nested project roots, which lets one repository scan cover monorepo subprojects without treating dependency trees or generated worktree mirrors as project input.

The scan keeps the input focused on files that can influence agent behavior. It skips known generated or dependency directories. It treats documentation-only CLAUDE.md files as source material but does not expand their neighboring agent directories unless a runtime companion shows that the directory is an active configuration root. Valid links are followed, while broken links are recorded so the scan can report missing configuration rather than stop. Relative paths in the scan result use forward slashes on every platform. References: src/…/discovery.ts• L8-22, src/…/discovery.ts• L138-195, src/…/discovery.ts• L315-340, src/…/paths.ts• L1-15, tests/…/discovery.test.ts• L463-539, tests/…/discovery.test.ts• L541-611

Configuration surfaces

Configuration surfaces are grouped by the kind of behavior they can describe. The type is a shared contract between discovery and the rule layer, so a rule can interpret content in the right security context without needing to rediscover the file.

SurfaceSecurity meaning
claude-mdInstructions that shape agent behavior or command use
settings-jsonPermissions, hooks, and related agent settings
mcp-jsonMCP server commands, arguments, and environment values
agent-mdAgent definitions and tool access
skill-md, rule-md, context-mdReusable agent behavior and supporting instructions
hook-script, hook-codeExecutable automation that can run during agent events
package-manager-configInstall and lifecycle settings that affect supply-chain risk
agents-md, command-mdShared agent instructions and user-invoked agent commands
codex-toml, hermes-yaml, harness-jsonSettings and behavior for other agent harnesses
plugin-manifestDeclarative plugin metadata and hook declarations
unknownDiscovered material that does not match a known analyzable type

Discovery also follows local hook references in hook settings and hook manifests. It adds an existing, repository-local script when a hook command names it, while rejecting URLs, absolute paths, home-directory paths, unknown variable roots, and paths outside the scan root. This links a declarative hook manifest to the implementation that may carry its real behavior. References: src/types.ts• L67-84, src/…/discovery.ts• L197-238, src/…/discovery.ts• L396-541, tests/…/discovery.test.ts• L245-329

Source context

Source context is the classification of where discovered content sits in the repository and how strongly it represents active runtime behavior. The scanner attaches this context to findings after rules run, so a risky pattern in a sample or plugin cache is not presented in the same way as a confirmed top-level setting.

The context model distinguishes the main cases below:

ContextMeaning for a finding
project-local-optionalA local settings file may not be used by every project user
docs-exampleThe pattern is in documentation, a sample, or a tutorial
plugin-cacheThe pattern is in installed plugin content on disk
plugin-manifestThe pattern is in a declarative hook definition
hook-codeThe finding is in executable code referenced by a hook

Documentation and plugin-cache context lowers structural risk by one severity step and adds a clear label. It does not lower secret findings because exposed credentials remain important even when they appear in examples or packaged content. Plugin manifest findings keep their severity but tell the reader to inspect the referenced implementation. References: src/source-context.ts• L1-55, src/…/index.ts• L67-119, src/…/index.ts• L122-195, tests/…/scanner.test.ts• L186-283, tests/…/scanner.test.ts• L285-426

The path model separates broad example signals from stronger documentation evidence. Broad signals help avoid treating sample-like paths as live roots, while the stronger form marks clear documentation or example locations for finding context. Plugin cache detection also works when the scan target is the .claude directory itself. References: src/source-context.ts• L1-70, tests/…/source-context.test.ts• L7-23

The context path also protects the boundary between examples and runtime configuration. A CLAUDE.md under an example-like directory is still scanned for real secrets and risky guidance. A directory with runtime companions is scanned more fully because its files can form a working configuration rather than a text-only example. This lets the analysis preserve useful coverage without overstating exposure. References: src/…/discovery.ts• L172-195, src/…/index.ts• L121-185, tests/…/discovery.test.ts• L463-522, tests/…/scanner.test.ts• L204-283

Static scan flow

The static scan flow transforms a target path into findings and related summaries. Discovery supplies typed file content and broken-link records. The rule engine evaluates each file with access to the complete file set, and source context qualifies the resulting findings before they are ordered for consumers.

The diagram shows how repository material becomes analyzable security output.

flowchart LR
    A[Target path] --> B[Repository discovery]
    B --> C[Typed file set]
    C --> D[Security rules]
    D --> E[Findings]
    E --> F[Source context]
    F --> G[Severity and runtime labels]
    C --> H[Broken-link findings]
    C --> I[Skill health]
    A --> J[Harness adapter detection]
    G --> K[Scan result]
    H --> K
    I --> K
    J --> K

The scanner runs every built-in and supplied rule against every discovered file. Rules can also receive the full file set, which supports checks that relate one configuration surface to another. Broken links become low-severity findings, while the final result also contains skill health and detected harness adapters. References: src/…/index.ts• L18-70, src/…/index.ts• L82-109, src/types.ts• L88-98, src/types.ts• L102-110

Configuration parsing

Configuration parsing turns TOML, YAML, JSON with common config-file variations, and markdown frontmatter into safe objects for checks that need structured values. Valid input keeps its normal meaning, while malformed input returns no object so a rule can fail closed instead of crashing the scan. References: src/…/parsers.ts• L1-27, src/…/parsers.ts• L39-72, tests/…/parsers.test.ts• L9-35

Vulnerable configuration corpus

The vulnerable configuration corpus is a set of small, in-memory configurations that model known risky agent setups. Each corpus entry has an ID, a human name, a risk category, typed file content, and expected rule findings. It gives the rule engine stable inputs for regression checks without requiring a real repository on disk.

The corpus covers the main attack shapes that the static checks must recognize:

  • Hardcoded secrets in instructions and MCP environment values.
  • Wildcard permissions without a deny list.
  • Hook exfiltration, reverse shells, listeners, and background processes.
  • MCP shell wrappers, remote commands, environment overrides, and unsafe package sources.
  • Prompt injection and instruction override patterns.
  • Privilege escalation and container escape behavior.
  • Persistence through cron jobs, shell profiles, and network listeners.
  • Stealth behavior such as log tampering, history clearing, and silent exfiltration.
  • Proxy hijacking, credential access, DNS exfiltration, and clipboard access.

These entries are test inputs rather than findings from the current repository. They describe the behaviors the analyzer must detect and the minimum rule coverage expected for each behavior. References: src/…/vulnerable-configs.ts• L5-20, src/…/vulnerable-configs.ts• L24-81, src/…/vulnerable-configs.ts• L86-215, src/…/vulnerable-configs.ts• L220-313, src/…/vulnerable-configs.ts• L319-449, src/…/vulnerable-configs.ts• L455-545

Corpus validation

Corpus validation runs the rule set against each corpus entry and compares the findings with the entry's expected rule IDs and minimum counts. It reports per-config results, category coverage, missing rules, extra rules, and recommendations when a category loses coverage.

The validation process follows a short sequence:

  1. Convert each corpus file into the same typed file shape used by repository discovery.
  2. Run each rule and group its findings by rule ID.
  3. Check that every expected rule reaches its expected minimum count.
  4. Summarize pass and fail results by configuration and risk category.
  5. Apply the corpus gate when a run must block on detection regressions.

The default corpus gate requires every configuration to pass. A lower detection threshold can support a temporary migration window, but the failed configurations and categories remain visible to automation. The command-line scan can run this validation with --corpus and can use --corpus-gate as a release or CI check. References: src/…/index.ts• L42-65, src/…/index.ts• L89-159, src/…/index.ts• L162-217, src/index.ts• L284-285, src/index.ts• L610-650

The corpus protects the contract between security rules and the behaviors they claim to detect. Structural checks ensure that entries have unique IDs, valid file types, non-empty content, valid severities, and rule IDs that exist in the built-in rule set. Regression checks then require the actual scanner to detect the expected attacks. References: tests/corpus.test.ts• L37-115, tests/corpus.test.ts• L214-244, tests/corpus.test.ts• L246-280

Change checklist

When these files or sections are changed, remember to consider these:

  • Update discovery and file-type handling together when adding a new configuration surface. A discovered file with the wrong type can silently bypass the rule that understands it.
  • Keep hook-reference resolution aligned with the path variables used by hook manifests. A new project-root variable can change whether implementation code is included in the scan.
  • Review source-context labels when adding repository paths for examples, plugins, or generated content. A path classification changes finding severity and reader interpretation.
  • Keep parser behavior aligned with the structured formats accepted by harness rules. A parser that rejects a valid config can silently remove evidence from analysis.
  • Preserve forward-slash paths in scan contracts when changing path handling. Rules and reporters compare these paths with literal repository locations.
  • Add or update corpus entries when a rule adds a new attack contract. Keep expected rule IDs and minimum counts aligned with the rule registry.
  • Preserve the strict corpus-gate behavior when changing validation thresholds or CLI wiring. A successful scan can otherwise hide a loss of category coverage.

Important failure modes

TriggerConsequenceGuard
A needed configuration directory is added outside the discovery surfaceIts content never reaches the rulesAdd the path to discovery and verify its ConfigFileType
A hook points to a repository-local script through an unsupported variableThe script is omitted and its behavior is not analyzedUse an approved project-root variable or extend path resolution with a scoped rule
Example-like paths are treated as active rootsDocumentation content can create over-stated runtime riskKeep example detection and runtime-companion checks aligned
A structural finding comes from docs or plugin cache contentThe result can look like confirmed active exposurePreserve source-context annotation and structural severity adjustment
A malformed TOML, YAML, JSON, or frontmatter file is handled as a scan errorOne bad config can stop or distort the wider analysisKeep safe parsers returning null and make rules handle absent structure
A broken symlink is treated as a readable fileDiscovery can crash or hide missing agent contentKeep broken links out of file inputs and emit a clear low-severity finding
A corpus entry names a removed or renamed ruleCorpus validation cannot verify the intended attackKeep expected rule IDs synchronized with the rule registry
A rule stops detecting an expected corpus behaviorThe corpus gate fails and signals scanner coverage lossInspect missing rules by config and category before changing the gate threshold

Key files

FileWhy to read it
src/…/discovery.tsDefines the repository material that enters static analysis and the boundary for referenced hook code
src/…/parsers.tsDefines safe handling for structured harness configuration and markdown frontmatter
src/…/paths.tsDefines the cross-platform path form used by scan results and rules
src/source-context.tsDefines path signals for examples and installed plugin caches
src/…/index.tsConnects discovery, rules, source context, broken-link findings, and the final scan result
src/types.tsDefines the shared file, finding, runtime-context, and scan-result contracts
src/…/vulnerable-configs.tsShows the attack-shaped inputs and expected rule coverage
src/…/index.tsDefines corpus validation, category reporting, and the regression gate
tests/…/discovery.test.tsShows the intended discovery boundaries, cross-platform path behavior, and hook-reference behavior
tests/…/parsers.test.tsShows the accepted structured formats and fail-closed parser behavior
tests/…/source-context.test.tsShows the difference between broad example paths and strong documentation signals
tests/…/scanner.test.tsShows how source context changes finding labels and severity
tests/corpus.test.tsShows the structural and regression guarantees for the vulnerable corpus