Rule detection system
The rule detection system turns commands, pasted text, files, and related runtime signals into structured findings or semantic facts. Built-in rule families cover unsafe execution shapes, deceptive text, credentials, network and package risk, configuration, Web3 actions, workflow artifact flow, and AI-facing content. Custom rules add organization-specific text or fact-based checks. The resulting detections are consumed by the command safety engine, then by policy and risk systems. See Policy and verdicts, Risk scoring and explanations, and Agent context and prompt safety.
Detection contexts
The engine evaluates input in one of three scan contexts. The context tells a rule family which facts exist and prevents a rule from treating missing data as a safe or matching value.
| Context | Input | Main detection focus |
|---|---|---|
exec | A command that is about to run | Command shape, URLs, packages, credentials, environment, operational context, and policy-linked state |
paste | Text being pasted into a terminal | Command and URL risk plus terminal deception, hidden content, prompt injection, and credential exposure |
file_scan | Content read from a file | File, code, configuration, rendered-content, CI, and AI-facing content |
The engine may inspect nested executable bodies as part of a command. This gives a wrapped or grouped command the same rule coverage as a top-level command. A bounded parser reports an incomplete analysis instead of trusting an unresolved command boundary. References: crates/…/extract.rs• L7-16, crates/…/engine.rs• L24-60, crates/…/engine.rs• L2695-2778
Built-in rule families
Built-in families inspect different views of the same input. Command rules use shell structure. URL and package rules use extracted values. File rules select themselves from the file path and content type. State-based families add signals from trusted local records or the current environment.
Command and shell rules
Command rules identify actions whose shape can fetch, execute, alter, expose, or hide content. They resolve common wrappers and shell quoting before they classify a command, so a command such as a download piped through a wrapper still exposes its effective interpreter and risk shape. The resolver separates proof of the executable name from proof of the full argument value. This lets a known home-relative executable receive normal analysis while still treating dynamic leaders or re-parsed arguments as unresolved.
Important groups include:
- Interpreter and download execution: pipes into shells or interpreters, remote content passed to an interpreter, inline PowerShell download-and-execute, and decode-then-execute forms.
- Privilege and system change:
sudoshells, privileged downloads and writes, broad permission changes, container privilege, and sensitive container mounts. - Destructive file actions: broad deletes or writes, empty-variable paths, recursive deletion, and
rsync --delete. - Installation and infrastructure: remote repository setup, unsigned trust, disabled package verification, remote Kubernetes or Helm input, and remote infrastructure modules.
- Network and data movement: suspicious destinations, command network policy violations, reverse shells, credential-file sweeps, and data exfiltration shapes.
The same shell view supports PowerShell, command prompt, POSIX, and related shell forms. The parser also bounds wrapper depth, nested executable analysis, token work, and the env -S re-parsing grammar. If it cannot prove the effective command within those limits, the engine emits an incomplete-analysis finding rather than classifying the outer command as safe. References: crates/…/command.rs• L45-60, crates/…/command.rs• L637-807, crates/…/command.rs• L862-1052, crates/…/command.rs• L1055-1126, crates/…/command.rs• L1134-1173
URL, path, transport, and ecosystem rules
URL-oriented rules inspect each extracted destination and its path before other command rules use it. They detect deceptive hosts and paths, unsafe transport, shortened destinations, suspicious registries, and ecosystem-specific install forms. Web3 parsing uses the same command view to describe network, RPC, signer, destination, and artifact facts for later safety decisions.
| Family | What it tries to establish |
|---|---|
| Host | Whether a destination uses confusable, non-ASCII, malformed, raw-IP, or look-alike host text |
| Path | Whether URL path text uses deceptive Unicode or encoding forms |
| Transport | Whether content reaches an execution sink over plain HTTP, an unclear scheme, a shortened URL, or disabled TLS checks |
| Ecosystem | Whether a URL or package reference points to a risky registry or package source |
| Threat intelligence | Whether a package, host, IP, or URL matches local or configured threat data |
The engine keeps URL extraction separate from URL classification. This lets several rule families explain different risks for one destination without changing the source text. References: crates/…/engine.rs• L2867-2900, crates/…/transport.rs• L5-75, crates/…/hostname.rs• L1-50, crates/…/path.rs• L1-45
Credential and environment rules
Credential rules look for known provider key shapes, private-key blocks, wallet material, and secret-like values in the contexts where exposed text is meaningful. Known matches and generic high-entropy matches use separate findings so a clear provider match is distinct from a heuristic secret signal. Structural checks can validate Web3 key material such as EVM private keys, recovery phrases, Solana keypairs, and encrypted wallet keystores. A credential assignment through an explicit environment-setting command is kept with the environment rule family to avoid duplicate reports.
Environment rules inspect both the process environment and command use of environment values. They surface proxy settings and can identify sensitive exports, interpreter hijacks, shell startup injection, and dynamic-linker code injection. Values in evidence are previewed or redacted rather than treated as ordinary command text. References: crates/…/credential.rs• L105-185, crates/…/command.rs• L3585-3721, crates/…/environment.rs• L30-80
Web3 command facts
The Web3 rule family describes blockchain command intent before a policy or later rule decides whether that intent is safe. It recognizes common Cast, Forge, Hardhat, Solana, and Anchor actions and records the selected network, RPC destination, operation, write mode, signer roles, destinations, artifacts, and safety flags.
The family emits bounded facts rather than a final finding at this stage. A signer can be a raw secret, a file, a wallet service, a hardware device, standard input, or a prompt. Secret-shaped values are not retained as ordinary references. Missing or conflicting selectors, unreadable static configuration, and other unresolved inputs remain part of completeness so downstream decisions do not mistake partial facts for proof.
The public fact model keeps a legacy single-signer and single-destination view alongside role-tagged and multi-destination views. This lets existing consumers read older data while newer consumers distinguish roles such as authority, fee payer, wallet, and program ID. References: crates/…/mod.rs• L1-30, crates/…/model.rs• L1070-1128, crates/…/model.rs• L1835-2070, crates/…/config.rs• L1-33
Terminal, rendered-content, and cloaking rules
These families inspect what a person may see rather than only the command grammar. Terminal rules detect control bytes, bidirectional controls, zero-width text, invisible Unicode, and other pasted or executed text that can change display or hide the true input. Rendered-content rules inspect HTML, Markdown, CSS, and PDF features that can conceal text. Cloaking rules compare server-delivered content with the view expected by a user.
Paste and output paths use byte-aware scanning because the dangerous signal can be outside normal text parsing. The scanner records offsets and byte or code-point descriptions for later evidence. Its bounded stream handling reports truncated or overflowing analysis instead of silently dropping a suspicious escape sequence. References: crates/…/extract.rs• L62-75, crates/…/extract.rs• L174-375, crates/…/terminal.rs• L1-42, crates/…/rendered.rs• L1-45
Configuration, code, CI, and AI-facing file rules
File rules select a detector from the file's path and content class. They are intended for repository and configuration review, not for treating every file as a command line.
| File surface | Detection goal |
|---|---|
| Configuration | Find injected directives, unsafe MCP server settings, malformed or hidden configuration, and suspicious configuration indicators |
| Source and scripts | Find dynamic execution, obfuscated payloads, and code that reads sensitive data before sending it over a network |
| CI and repository automation | Find unpinned actions or images, dangerous triggers, untrusted input, excessive permissions, and unsafe package scripts |
| AI-facing files | Find hidden notebook content, suspicious notebook output, concealed agent instructions, and script or external-reference content in SVG files |
| Rendered documents | Find hidden HTML, CSS, Markdown, and PDF text that a human may not notice |
AI-facing files are a distinct surface because an agent can process content that a human reviewer does not see. The scan covers recognized instruction files, notebooks, SVGs, and related configuration paths. It does not treat visible instructions as hidden-content findings, and file scans do not apply command-line prompt-injection checks to ordinary documentation. References: crates/…/engine.rs• L2695-2778, crates/…/codefile.rs• L8-42, crates/…/cifile.rs• L1-55, crates/…/aifile.rs• L1-109, crates/…/configfile.rs• L10-89
Prompt-injection rules
Prompt-injection rules inspect paste content and agent or tool output for known instruction-override, role-override, and jailbreak phrases. They route direct matches into separate high-severity families so policy can distinguish an instruction override from a broader prompt-injection marker.
The detector also checks bounded normalized forms of the input. A phrase found only after deobfuscation receives a distinct obfuscated-injection finding that records the defeated transform. Custom seed phrases can extend the built-in set, but invalid or over-budget seeds are rejected with safe indexed diagnostics. This family is a seed detector, not a complete defense; agent output remains untrusted even when no seed matches. References: crates/…/prompt_injection.rs• L1-32, crates/…/prompt_injection.rs• L112-199, crates/…/prompt_injection.rs• L399-545
Workflow artifact flow rules
Workflow artifact rules inspect the repository as a whole to find a trust break between an untrusted build and a privileged workflow. They connect a fork- or pull-request-reachable producer, its uploaded artifact, a workflow_run consumer that downloads the triggering run's artifact, and a later execute, source, path-change, publish, or deploy action.
The rule emits WorkflowArtifactPoisoning only when the full producer-to-consumer chain is proven and no trusted digest or attestation protects the bytes first. Unknown conditions, dynamic artifact names, unmodelled actions, relays, and incomplete repository coverage preserve an incomplete state rather than proving that no unsafe flow exists. References: crates/…/workflow_artifacts.rs• L1-42, crates/…/workflow_artifacts.rs• L146-212, crates/…/workflow_artifacts.rs• L1891-2044, crates/…/workflow_artifacts.rs• L2058-2171
Operational-context and state rules
Some risks depend on where or how a command runs rather than on its text alone. Context rules combine a recognized cloud, Kubernetes, SSH, infrastructure, or container target with labels and local state to identify production changes, destructive remote actions, or privileged operations.
Other state rules inspect facts that persist outside one command. Examples include executable provenance, repository hooks, shell persistence changes, tainted downloaded files, command cards, repository command manifests, canary tokens, clipboard source mismatch, AI configuration drift, and cross-event sequences. These rules are not all hot-path pattern checks. They run when their related command, scan, or state signal is available.
Cloud context detection identifies the active Kubernetes, AWS, Google Cloud, or Azure context without reading credential values. The result is represented as a provider and operator-facing context name, then matched to labels used by operational-context rules. Failures and missing configuration remain distinct so audit output can show whether a context was absent or could not be read. References: crates/…/context_detect.rs• L1-30, crates/…/context_detect.rs• L45-139, crates/…/verdict.rs• L326-412, crates/…/verdict.rs• L450-709
Custom rule families
Custom rules extend the built-in detector without changing the engine. A custom rule declares one matcher: a regular expression over the input or a when clause over facts already extracted by the engine. Both forms carry a user rule ID, title, description, severity, and scan contexts.
Pattern rules
Pattern rules match text in the selected exec, paste, or file contexts. They are useful for organization-specific host names, command fragments, tokens, or file content. Their finding uses the shared CustomRuleMatch rule ID and stores the user-defined ID in custom_rule_id, so downstream systems can tell which custom rule matched. Invalid patterns, overlong patterns, and rules without a usable context are skipped before matching. Diagnostic text is redacted so a bad rule ID or error cannot put secrets, paths, or control bytes into logs. References: crates/…/custom.rs• L8-27, crates/…/custom.rs• L53-127, crates/…/custom.rs• L196-238
Semantic predicate rules
Semantic rules use a Boolean tree of facts instead of matching raw text. all, any, and not combine predicates from these fact families:
- Command: pipeline target,
sudouse, and current working directory. - URL: host, host pattern, scheme, reputation, and domain allow-list relation.
- Package: ecosystem, package-name pattern, and reputation.
- File: scanned file path pattern.
The engine builds this context from the same extraction used by built-in rules. URL reputation uses known-domain and local signed threat data. Package reputation distinguishes known, unknown, malicious, and no-database states; no network lookup occurs while the rule evaluates. Regex predicates reuse compiled patterns within a bounded cache, so policy changes cannot retain an unbounded set of old patterns. References: crates/…/custom_rule_dsl.rs• L50-97, crates/…/custom_rule_dsl.rs• L284-344, crates/…/custom_rule_dsl.rs• L688-725, crates/…/engine.rs• L63-169
Context validation
Custom rules declare where they run, but a semantic clause also has a set of contexts where all its facts are available. The rule system computes that set per clause: all needs the intersection of its child contexts, any uses their union, and not stays within its child's context. The engine stores only the declared contexts that can fully evaluate the clause.
Unavailable facts evaluate to Unknown. Strong three-valued logic keeps not(Unknown) as Unknown, and only True fires a semantic rule. Unsupported agent.kind and mcp.tool predicates are rejected because no scan context supplies those signals. Invalid regexes, overlong patterns, malformed shapes, unsupported predicates, excessive nesting, and rules with no usable context are skipped during loading and reported by rule validation. References: crates/…/custom_rule_dsl.rs• L151-170, crates/…/custom_rule_dsl.rs• L346-386, crates/…/custom_rule_dsl.rs• L508-630, crates/…/custom_rule_dsl.rs• L829-880, crates/…/custom.rs• L75-191
Detection representation
Every emitted detection is a Finding. A finding names its stable rule_id, severity, title, description, supporting evidence, and optional enrichment or custom-rule identity. The stable rule ID is the contract used by policy overrides, verdict generation, audit output, webhooks, and other consumers.
Web3 analysis also produces structured command facts for later safety decisions. These facts carry operation and write intent, network and RPC details, signer and destination references, artifacts, safety flags, source spans, and completeness. They are not themselves a verdict. Raw signer material is omitted or privacy-projected, and incomplete facts remain distinguishable from known-safe facts.
Evidence records the kind of fact that supports the detection. The main evidence forms are:
Urlfor the raw destination.CommandPatternfor a command shape and matched preview.ByteSequencefor an offset and byte or code-point signal.EnvVarfor an environment name and redacted value preview.Textfor a short detector-specific explanation.ThreatIntelfor a source, threat type, confidence, and optional reference.HostComparisonandHomoglyphAnalysisfor deceptive-name detail.
The representation keeps the detection reason separate from the final action. Severity can be adjusted by policy within its allowed limits, while the policy and verdict system derives whether the overall result allows, warns, or blocks. human_view and agent_view are optional enrichments that describe the human-visible and AI-processed sides of a finding. References: crates/…/verdict.rs• L912-1033, crates/…/model.rs• L2055-2070, crates/…/model.rs• L2172-2227, crates/…/engine.rs• L3174-3177
Detection flow
The flow below shows how an input moves from context selection through extraction and family checks to structured findings or facts.
flowchart TD
A[Command, paste, or file input] --> B[Select scan context]
B --> C[Fast signal and shell-aware gate]
C --> D[Extract command, URL, package, byte, and file facts]
D --> E[Run applicable built-in families]
D --> F[Evaluate applicable custom rules]
E --> G[Create findings or semantic facts]
F --> G
G --> H[Apply policy severity and verdict rules]
The fast gate skips work only when no enabled family can match. Semantic custom rules and state-backed families can force the full pass when their resolved runtime context applies, even when no coarse text signal appears. File scans always continue to file-oriented analysis because their purpose is content coverage. Web3 facts and repository workflow analysis can retain incompleteness so later systems do not interpret missing coverage as a clean result. References: crates/…/engine.rs• L2387-2592, crates/…/engine.rs• L2664-2778, crates/…/engine.rs• L2867-3171, crates/…/custom.rs• L273-360, crates/…/coverage.rs• L164-180, crates/…/workflow_artifacts.rs• L1918-2044
Change checklist
When these files or sections are changed, remember to consider these:
- Keep
RuleIdnames aligned with rule producers, policy severity overrides, serialized output, and explanation metadata. - Keep each custom DSL predicate's declared context, backing fact, satisfiable-context calculation, runtime evaluation, and fast-gate forcing logic in sync.
- When adding a semantic-only rule family, update the context-aware fast-gate forcing logic so a clean coarse scan cannot skip an applicable match.
- When adding a file family, update path classification and file-scan dispatch so the file is selected without enabling command rules.
- When changing evidence fields, preserve redaction and the wire shape used by JSON, SARIF, audit, and webhook consumers.
- When adding state-backed detections, define whether the rule runs on the hot path or only in an explicit scan and how absent state is represented.
- When changing Web3 facts, keep role-tagged and legacy projections compatible and preserve the distinction between raw secrets, public references, and incomplete selectors.
- When changing workflow artifact analysis, keep producer reachability, triggering-run binding, artifact identity, containment, and trusted verification aligned across the repository post-pass.
- When changing command normalization or wrapper parsing, keep command-name resolution, full-argument proof, network policy, nested analysis, and incomplete findings aligned.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
A custom when clause mixes facts that no one scan context provides | The rule would be dead or could match from absent data | Per-clause context algebra rejects unsatisfiable rules and runtime evaluation preserves Unknown |
| A semantic-only custom rule has no coarse text trigger | A fast exit could skip a real match | The engine forces the full pass only for a rule's resolved runtime context |
A custom when clause is deeply nested or its regex is too large or invalid | Policy loading could consume excess work or create a dead rule | Deserialization depth and regex limits reject the rule before matching |
| A command wrapper, dynamic leader, or nested executable body exceeds the parser boundary | The effective command is unknown | The engine emits AnalysisIncomplete and uses a conservative result |
A command name is known but a re-parsed argument such as env -S is dynamic or malformed | A wrapper could be analyzed as a different command than the shell will run | The dedicated bounded parser fails closed and reports incomplete analysis |
| A file is too large, unreadable, unsupported, or a scan rule panics | The scan could look clean despite missing coverage | The scan records a typed coverage gap and exposes incomplete analysis |
| Credential-like text is included in finding evidence | Secrets could leak into logs or downstream records | Credential matches, environment values, and custom-rule diagnostics use redacted or descriptive evidence |
| Cloud context detection reads a changed or broken provider setup | A production label could be applied to stale context data | Context inputs are fingerprinted, cached briefly, and failures are exposed |
| Web3 selectors or signer references are missing, conflicting, or dynamic | A later policy could treat an incomplete blockchain action as known-safe | Web3 facts carry completeness and unresolved sources instead of guessing |
| A privileged workflow consumes an artifact from an untrusted run without trusted verification | Attacker-controlled build bytes can reach execution or publish and deploy sinks | Repository correlation requires the complete chain and emits WorkflowArtifactPoisoning |
| Prompt-injection text is encoded or paraphrased beyond the seed set | The detector can miss the instruction | Output remains untrusted; normalized-seed coverage is bounded and explicitly not complete |
Key files
| File | Why to read it |
|---|---|
| crates/…/engine.rs | Shows context selection, fast-gate behavior, extraction, family dispatch, custom-rule evaluation, and finding finalization |
| crates/…/verdict.rs | Defines stable rule IDs, severity, evidence, and the finding contract |
| crates/…/extract.rs | Defines scan contexts, byte signals, URL extraction, and streamed output signals |
| crates/…/command.rs | Explains shell-aware command facts, bounded command resolution, and command-shape coverage |
| crates/…/custom.rs | Shows custom regex and semantic-rule compilation, context clamping, diagnostics, and matching |
| crates/…/custom_rule_dsl.rs | Defines semantic predicates, context validation, bounded clause parsing, and three-valued evaluation |
| crates/…/credential.rs | Shows known-pattern, private-key, wallet-material, and high-entropy credential detection |
| crates/…/environment.rs | Shows process-environment proxy detection and redacted environment evidence |
| crates/…/mod.rs | Defines the Web3 fact surface and its bounded parser exports |
| crates/…/model.rs | Defines Web3 operations, safety facts, signer roles, destinations, artifacts, and wire-safe representations |
| crates/…/aifile.rs | Defines the AI-facing file surface and hidden-content goals |
| crates/…/prompt_injection.rs | Defines built-in and custom prompt-injection seeds and obfuscation findings |
| crates/…/workflow_artifacts.rs | Defines repository-level artifact poisoning analysis and its proven-chain finding |
| crates/…/scan.rs | Shows file-scan coverage, workflow post-pass plumbing, and incomplete-scan representation |
| crates/…/context_detect.rs | Defines operational provider-context signals and their failure semantics |