Introducing a new way to review your PRs.

Read the announcement

sheeki03 / tirith

Terminal security for developers and AI agents. Intercepts homograph URLs, pipe-to-shell, ANSI injection, obfuscated payloads, data exfiltration, and malicious AI skills/configs before they execute.

View on GitHub

19 documents · Updated Nov 23, 2026

docs / command-safety-engine

Command safety engine

The command safety engine evaluates a command, script, pasted text, file, or execution output in its real shell and runtime context. It combines fast checks, structured extraction, rule analysis, policy state, and execution evidence to produce safety findings and an action for the caller. See Rule detection system, Policy and verdict decisions, and Risk scoring and explanations for the child views of those concerns.

Analysis subjects

The engine accepts one analysis context that tells it what the input represents and which surrounding facts can affect the result. This keeps the same safety model across interactive checks, paste protection, repository scans, downloaded scripts, and streamed output.

SubjectSafety questionMain context
CommandWhat will the shell execute, and what does it target?Shell type, current directory, interactive state
ScriptWhat does the script reference or invoke?Interpreter, script bytes, execution intent
PasteCan hidden or altered content affect the terminal or an agent?Raw bytes, clipboard HTML, source record
FileDoes file content carry a configuration, code, supply-chain, or hidden-content risk?File path, repository root, file kind
OutputDoes returned content contain terminal control, injection, or data-loss signals?Stream chunks and retained scan state

The engine keeps command text, raw bytes, shell type, scan context, working directory, file path, repository scope, and selected sidecar state together in AnalysisContext. The context does not itself decide the result; it gives each analysis stage the facts needed to interpret the same text safely. References: crates/…/engine.rs• L295-320, crates/…/extract.rs• L7-17

Analysis pipeline

The analysis pipeline moves from cheap boundary checks to deeper parsing and rule evaluation. It can stop early for an input with no relevant signal, but policy and runtime-state triggers can require the complete pass.

This diagram shows how an input becomes a verdict while preserving context for later stages.

flowchart LR
    A[Input and context] --> B[Tier 0 bypass and state checks]
    B --> C[Tier 1 byte and pattern checks]
    C -->|No signal or trigger| D[Fast Allow]
    C -->|Signal or forced full pass| E[Tier 2 policy and threat data]
    E --> F[Tier 3 shell-aware extraction and rules]
    F --> G[Severity and policy overlays]
    G --> H[Verdict with findings and action]
    H --> I[Caller: warn, block, score, explain, or execute]

Tier 0 records bypass requests and other state that must be visible to enforcement. Tier 1 checks raw bytes and coarse patterns. It also checks shell-effective text and nested executable bodies so quoting, wrappers, or encoded inner commands cannot hide the need for deeper analysis. Tier 2 resolves the effective policy and local threat data. Tier 3 parses URLs and command structure, runs the applicable rule families, applies policy filters, and builds the final verdict. Command analysis has explicit work and nesting limits; when the engine cannot finish a command boundary, it emits an incomplete-analysis finding instead of a clean result. References: crates/…/engine.rs• L2668-2928, crates/…/engine.rs• L2999-3032, crates/…/engine.rs• L3165-3655, crates/…/command.rs• L45-60, crates/…/command.rs• L862-1052

The fast path is an optimization rather than a different safety decision. Before it returns a clean result, the engine resolves the effective policy and checks whether custom rules, custom paste seeds, deobfuscation candidates, runtime stores, cards, manifests, execution guards, or other context require the complete pass. File scans always continue to the file-oriented analysis path. References: crates/…/engine.rs• L2687-2928, crates/…/engine.rs• L3042-3163

Shell and content interpretation

Shell-aware interpretation turns command text into execution-shaped facts before rules inspect it. The engine supports POSIX shells, Fish, PowerShell, and Windows Command Prompt, and it carries the selected shell into nested bodies so a wrapper cannot change the meaning of the inner command without analysis.

The interpretation stage has two linked views:

  • An evidence view preserves the source text for findings and audit.
  • An execution view reflects shell word boundaries, wrappers, pipelines, substitutions, and the body that will run.

Tokenization identifies command segments, arguments, separators, and source ranges. URL extraction then classifies standard URLs, SSH-style references, Docker image references, schemeless sink targets, and malformed URL-like text. Normalization exposes safe-to-decode forms and suspicious encoded or non-ASCII content without turning encoded separators into new shell structure. Command-position analysis also resolves known execution wrappers and shell quoting before it classifies the command that will run. References: crates/…/tokenize.rs• L3-50, crates/…/extract.rs• L1571-1881, crates/…/parse.rs• L4-35, crates/…/normalize.rs• L60-85, crates/…/command.rs• L392-807, crates/…/command.rs• L1212-1357

Nested executable content is analyzed as part of the same invocation. This covers shell substitutions, interpreter wrappers, decoded command bodies, and the second-stage argument grammar of forms such as env -S while bounding recursion and work. The engine reports incomplete nested analysis when it cannot establish what will execute, which lets enforcement treat uncertainty as a safety signal instead of treating the outer command as authoritative. References: crates/…/engine.rs• L22-60, crates/…/engine.rs• L2742-2751, crates/…/engine.rs• L3165-3174, crates/…/engine.rs• L3424-3445, crates/…/command.rs• L80-317, crates/…/command.rs• L1134-1209

The command model separates a known literal path from a dynamic command leader. Literal home paths, shell test forms, alias-listing forms, and local package paths can remain clean during a full check. Dynamic leaders, wildcarded executable paths, unresolved wrapper bodies, and reparsed values remain incomplete and are blocked when the engine cannot prove the executed command. References: crates/…/command.rs• L637-807, crates/…/shell_false_positive_regressions.rs• L33-96, crates/…/shell_false_positive_regressions.rs• L98-167

Analysis contexts

Each context enables the checks that match its risk boundary. A command check focuses on execution and policy. A paste check adds raw-byte, clipboard, and prompt-injection analysis. A file scan selects rules from the file path and does not treat file text as a command line. Output analysis uses a stateful stream path because dangerous content can cross chunk boundaries.

ContextWhat it emphasizesWhat it avoids
ExecShell semantics, targets, environment, privilege, provenance, and execution guardsPaste-only clipboard and prompt-content assumptions
PasteTerminal deception, hidden content, prompt injection, exfiltration, and source mismatchTreating pasted prose as a shell command by default
FileScanCode, configuration, CI, AI-facing files, rendered content, and lock driftCommand, environment, and URL sink rules
Output streamTerminal control, fake prompts, prompt injection, exfiltration, and canariesA single-buffer assumption

File analysis also assigns one content owner before applying content-specific checks. PDF and other rendered content use their own text view, while ambiguous polyglot content becomes incomplete instead of being passed to conflicting analyzers. This prevents lossy or mixed-format input from being treated as a complete clean scan. References: crates/…/engine.rs• L3042-3163, crates/…/engine.rs• L3772-3785

The output path keeps bounded state and scans both each chunk and an overlap with the prior tail. Finalization closes open escape sequences and performs the end-of-stream checks, so a partial or split signal does not disappear at a buffer boundary. It also keeps confirmed supported-secret material separate from an analysis-budget failure; incomplete analysis is not treated as proof that a secret was present. References: crates/…/engine.rs• L646-689, crates/…/engine.rs• L718-876, crates/…/engine.rs• L900-949

Interactive shell boundaries

Interactive shell hooks place the analysis engine between a user action and shell execution. They check an accepted command before it runs and send pasted text through the paste context, while preserving the shell family and current working directory needed for correct interpretation. References: crates/…/bash-hook.bash• L802-883, crates/…/fish-hook.fish• L351-405, crates/…/zsh-hook.zsh• L333-655

The hooks use a shell-bound receipt when the engine approves execution. A receipt binds the checked command to the interactive shell and its execution boundary, so a changed command, malformed response, failed capture, or unresolved earlier receipt stops line acceptance rather than allowing an untracked command to run. When the receipt capability is unavailable, the hooks show a degraded state and use their legacy check path instead of claiming stronger evidence. References: crates/…/bash-hook.bash• L310-356, crates/…/bash-hook.bash• L395-446, crates/…/fish-hook.fish• L135-267, crates/…/fish-hook.fish• L408-580, crates/…/zsh-hook.zsh• L140-269, crates/…/zsh-hook.zsh• L338-480

Shell setup pins the native Tirith executable and required helper programs when the hook loads. It ignores later PATH changes, aliases, functions, stale command caches, and relative PATH entries for these safety operations. If startup prerequisites are missing, the hook leaves the user's input binding unchanged and reports that protection is off; if an active hook loses a required boundary, it blocks or degrades visibly rather than hiding the loss. References: crates/…/tirith.sh• L6-51, crates/…/bash-hook.bash• L96-179, crates/…/fish-hook.fish• L21-87, crates/…/zsh-hook.zsh• L24-89, crates/…/shell_helper_portability.rs• L216-277, crates/…/shell_helper_portability.rs• L298-412

The shell conformance boundary is tested as a delivery contract rather than only as a parser result. Allowed input must run once and stay visible. Blocked input must not run. Prompt, paste, wrapper, and shell-helper changes must preserve this distinction across Bash, Zsh, and Fish. References: crates/…/shell_conformance.rs• L1-23, crates/…/shell_conformance.rs• L230-390, crates/…/shell_conformance.rs• L1231-1249, crates/…/shell_helper_portability.rs• L87-160

Findings and verdicts

A finding is one concrete safety signal with a stable rule identity, severity, title, description, and evidence. Evidence links the signal to a command pattern, URL, text span, file, or other subject detail so downstream surfaces can explain the result without re-running analysis.

The verdict is the engine's compact result. It carries all findings plus the action, analysis tier, timing data, bypass facts, policy path, extracted-URL count, approval state, caller origin, and audit-only context. The action uses the strongest finding severity: Critical or High blocks, Medium or Low warns, and Info alone allows. References: crates/…/verdict.rs• L1921-1941, crates/…/verdict.rs• L2053-2077, crates/…/verdict.rs• L2881-2933, crates/…/verdict.rs• L3038-3087

The engine applies severity overrides, allowlist and blocklist effects, baseline annotations, and enrichment before it returns the verdict. Some context records explain why a result was reached without changing the action; this preserves the boundary between evidence and enforcement. The action can then receive a policy or session-based upgrade, but the engine does not silently downgrade a stronger result. References: crates/…/engine.rs• L3545-3713, crates/…/escalation.rs• L19-84

Public finding and verdict views are redacted. Presentation also has bounded finding, evidence, and JSON budgets; it can omit detail and mark the result incomplete without changing the action that was derived from the complete internal finding set. References: crates/…/verdict.rs• L1976-2001, crates/…/verdict.rs• L2080-2281, crates/…/verdict.rs• L2283-2399, crates/…/verdict.rs• L2500-2614

Safe command guidance

Safe command guidance proposes a less risky command after a finding, but it is advisory unless the exact replacement is independently checked through the trusted CLI-inline path. This keeps a rewrite from becoming an unintended policy or execution bypass.

Generic callers receive remediation text and may receive a candidate command for display, but they do not receive an executable safe_command value. The CLI-owned path repeats the same analysis with the same shell, policy, session, origin, and runtime threat mode for each candidate. Only a final candidate that reaches approval-free Allow can cross the executable suggestion boundary. References: crates/…/safe_command.rs• L33-47, crates/…/safe_command.rs• L55-130, crates/…/safe_command.rs• L267-313

The verification path can compose compatible rewrites, but it bounds the search and discards partial candidates when no exact allowed result exists. This makes “no executable rewrite” the safe outcome when command semantics or provenance remain uncertain. References: crates/…/safe_command.rs• L322-417

Script review and execution state

Downloaded script review uses the same engine with an interpreter-aware context. The review identifies the interpreter, validates the script bytes, and performs static reference checks. For supported command interpreters it then runs the full command analysis; for unsupported, invalid, or incomplete content it records incomplete analysis and refuses live execution rather than presenting an incomplete result as clean. References: crates/…/runner.rs• L1461-1561, crates/…/runner.rs• L1563-1624

Remote execution first binds the download request to its transport, size, redirect, and optional digest checks. It then reviews the exact downloaded bytes. The later launch uses those same bytes and the selected interpreter rather than reopening a mutable cache path. References: crates/…/runner.rs• L1284-1441, crates/…/runner.rs• L2435-2505, crates/…/runner.rs• L2752-2774

When execution is requested, the reviewed bytes and interpreter remain bound to the later decision. The runner rechecks the exact content after confirmation, requires a complete verdict, and separates a policy refusal from a user cancellation or a non-executing inspection. References: crates/…/runner.rs• L1764-1851, crates/…/runner.rs• L2569-2749

Execution state carries a frozen decision basis and evidence grade. A prepared execution binds the command shape, policy basis, verdict basis, session generation, shell, interaction requirements, and bypass facts. The execution gate rechecks those facts while holding the stable session lock before it permits a launch. References: crates/…/execution_state.rs• L294-349, crates/…/execution_state.rs• L677-807, crates/…/execution_state.rs• L984-1131, crates/…/execution_state.rs• L1890-1977, crates/…/execution_state.rs• L3680-3713

Only evidence from a confirmed execution boundary is recorded as confirmed execution. Kernel execution stop and exact gateway completion can confirm a record; shell or gateway-forward observations remain unresolved and can later upgrade only through a compatible evidence path. Durable records retain privacy-bounded hashes and redacted previews rather than raw commands, policy objects, or unredacted findings. References: crates/…/execution_state.rs• L167-197, crates/…/execution_state.rs• L487-574, crates/…/execution_state.rs• L3808-3970

Child analysis pages

The engine provides the shared analysis path. The following pages describe the three major decisions that follow from it:

Change checklist

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

  • Changes to AnalysisContext must stay aligned with every caller that creates execution, paste, file, script, or output context.
  • Changes to Tier 1 triggers must preserve the rule families and runtime stores that need to force a full pass.
  • Changes to shell token or URL extraction must preserve both source evidence and shell-effective nested analysis.
  • Changes to command wrapper resolution, interpreter names, or command work limits must preserve the incomplete-analysis boundary and the custom-rule command facts.
  • Changes to Finding or Verdict fields must preserve the action derivation, redacted views, and bounded presentation contract.
  • Changes to safe-command transformations must preserve the distinction between guidance and an exact CLI-verified executable suggestion.
  • Changes to script interpreter support or download validation must update the completeness boundary before any live execution path can accept the interpreter or content.
  • Changes to shell hooks, receipt framing, or helper pinning must preserve one-time delivery, command-to-receipt binding, and honest protection status across all supported shells.
  • Changes to execution evidence must keep unresolved observations separate from confirmed execution history and preserve draft rechecks.

Important failure modes

TriggerConsequenceGuard
Nested shell body is dynamic, malformed, or too deepThe engine cannot prove the executed body and may block when provenance guarding is activeEmit AnalysisIncomplete instead of trusting the outer command
A custom rule or runtime guard exists but no full-pass trigger is addedA clean Tier 1 result can skip a rule that should affect enforcementForce Tier 3 whenever applicable policy or runtime state can add findings
Command wrapper parsing or env -S reparsing exceeds its boundAn inner command can remain unknown at the enforcement boundaryTreat the omitted suffix or unresolved wrapper as a high-severity incomplete analysis
Script bytes are not valid UTF-8, the interpreter has no complete analyzer, or the download request fails its transport or digest checksLive execution could occur without a complete review or with untrusted contentRefuse before interpreter launch and require validated exact bytes
A proposed safe command is not re-analyzed by the producer-owned CLI pathA rewrite could appear safe while still carrying the original risk or a new oneKeep safe_command empty unless the exact final command reaches approval-free Allow
Output ends inside a dangerous escape sequence or exceeds a supported-secret analysis budgetA partial terminal payload or incomplete secret scan could be missedFinalize the stream and block on incomplete analysis where required
Shell hook capture, receipt framing, or command-to-buffer matching failsThe checked command may not match the command that reaches the shellReject line acceptance, retire or retain the receipt for recovery, and show the protection state
A policy or verdict changes between review and executionThe process could run content under a decision that no longer matches itRe-analyze exact bytes and bind the launch decision to policy and verdict digests under the execution gate

Key files

FileWhy to read it
crates/…/engine.rsDefines the shared analysis context, tiered flow, context routing, policy gate, and final verdict assembly.
crates/…/command.rsDefines shell-aware command resolution, wrapper handling, bounded command analysis, and command facts used by analysis rules.
crates/…/extract.rsShows how shell text, raw bytes, nested bodies, and URL-like targets become analysis inputs.
crates/…/tokenize.rsShows the shell model used to preserve command boundaries across supported shells.
crates/…/verdict.rsDefines findings, actions, verdict data, redaction, and bounded output contracts.
crates/…/safe_command.rsShows how advisory rewrites are separated from exact CLI-verified executable suggestions.
crates/…/runner.rsShows how validated script content and interpreter choice connect review to refusal or execution.
crates/…/execution_state.rsDefines the frozen decision, execution gate, evidence grades, and durable execution history.
crates/…/bash-hook.bashShows the Bash boundary between interactive input, analysis, receipt evidence, and execution.
crates/…/fish-hook.fishShows the Fish command and paste boundary and its receipt handling.
crates/…/zsh-hook.zshShows the Zsh line-accept and bracketed-paste boundary.
crates/…/tirith.shShows how the shell loader selects a supported interactive hook.
crates/…/shell_false_positive_regressions.rsDemonstrates the boundary between benign static shell forms and dynamic commands that must remain incomplete.
crates/…/shell_conformance.rsVerifies that shell interception delivers allowed commands once and stops blocked commands.
crates/…/shell_helper_portability.rsVerifies pinned helper discovery and private capture behavior on non-standard layouts.
crates/…/scan.rsShows how file scans report analyzed results and coverage gaps instead of silent skips.
crates/…/scoring.rsShows the boundary where findings become a reproducible risk score.