@agenttrail/guardrails 0.0.1-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,304 @@
1
+ <!-- cspell:words kubeconfig -->
2
+
3
+ # @agenttrail/guardrails
4
+
5
+ **A library of rules that spot dangerous commands before an AI coding agent runs them.**
6
+
7
+ 56 rules, grouped into 8 packs. Apache-2.0.
8
+
9
+ ---
10
+
11
+ ## What this is, in plain terms
12
+
13
+ When you let an AI coding agent work in your terminal, it eventually proposes something you would
14
+ not have typed yourself — `git reset --hard` over a day's work, `rm -rf` on the wrong path, a
15
+ `terraform apply` against production.
16
+
17
+ This package is the **list of things worth stopping**, written as data. Each entry says what to look
18
+ for, how serious it is, and what should happen — allow it, ask a human first, or refuse.
19
+
20
+ **That is all this package does.** It contains no code that watches your machine and nothing that
21
+ talks to the network. It is a list. Something else has to read it and act on it — normally
22
+ [`agenttrail-guard`](https://github.com/agenttrailhq/guard), which runs on your laptop and checks each
23
+ command an agent proposes against these rules.
24
+
25
+ Separating the two is deliberate. You can read every rule here, disagree with one, and change it,
26
+ without trusting anything about the tool that enforces them.
27
+
28
+ ## Who this is for
29
+
30
+ - **You use an AI coding agent** and want a sensible default set of guardrails rather than writing
31
+ your own from scratch.
32
+ - **You want to see exactly what is being blocked and why.** Every rule is plain data with a written
33
+ explanation, including what it *misses*.
34
+ - **You want to contribute a rule** you wish had existed. See [Contributing](#contributing-a-rule).
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ npm install @agenttrail/guardrails
40
+ ```
41
+
42
+ Most people never install this directly — `agenttrail-guard` bundles it. Install it yourself if you
43
+ are writing rules, or building your own tool on top of the list.
44
+
45
+ ## A rule, start to finish
46
+
47
+ Here is a complete rule. Nothing is hidden; this is the actual shape.
48
+
49
+ ```jsonc
50
+ {
51
+ "id": "wt.reset-hard",
52
+ "category": "working-tree",
53
+ "severity": "high",
54
+ "defaultAction": "block",
55
+ "title": "git reset --hard discards uncommitted work",
56
+ "description": "Discards all uncommitted changes. Does not match `git restore` — see wt.restore-path.",
57
+
58
+ // What to look for. This one matches a Bash command against a regular expression.
59
+ "match": {
60
+ "any_of": [
61
+ { "kind": "execute_tool", "label": "Bash", "detail_matches": ["\\bgit\\s+reset\\s+--hard\\b"] }
62
+ ]
63
+ },
64
+
65
+ // Proof it works, in both directions — see "Every rule proves both directions" below.
66
+ "fixtures": {
67
+ "block": ["git reset --hard"],
68
+ "allow": ["git reset src/api.ts"]
69
+ }
70
+ }
71
+ ```
72
+
73
+ Reading the fields:
74
+
75
+ | Field | What it means |
76
+ |---|---|
77
+ | `id` | A stable name. Users type it to disable or change a rule, so it never changes. |
78
+ | `severity` | How bad the thing being caught is: `critical`, `high`, `medium`, `low`, `info`. **It is not a price** — this package ships no mapping from severity to money. |
79
+ | `defaultAction` | What should happen: `block` (refuse), `require_approval` (ask a human), or `warn` (allow, but say so). A user can override it. |
80
+ | `description` | What the rule catches **and what it misses**. The honest limits are part of the rule, not a footnote. |
81
+ | `match` | The condition. `any_of` means "any one of these is enough". |
82
+ | `fixtures` | Examples that must match, and examples that must not. |
83
+
84
+ ## The eight packs
85
+
86
+ A rule is filed by **the harm it prevents**, never by the technique it uses to spot it.
87
+
88
+ That sounds like a detail and is not. The three rules about production config, `.env` files and API
89
+ endpoints all work by matching file paths — but they are *not* in `file-scope`. Someone who turned
90
+ that pack off to stop path noise would otherwise silently lose their production and secret
91
+ protection, which they never asked to turn off and would not know they had.
92
+
93
+ | Pack | Rules | What it is about |
94
+ |---|---:|---|
95
+ | `working-tree` | 9 | Destroying uncommitted work or published history — `git reset --hard`, `git clean -fd`, force-push, `rm -rf`. |
96
+ | `destructive-data` | 8 | Data git cannot bring back — a dropped volume, a dropped database, destructive DDL, a deleted shadow copy. |
97
+ | `prod-infra` | 8 | Changing running infrastructure — Terraform, Kubernetes, Helm, cloud deletes, a deploy that names production. |
98
+ | `secret-exposure` | 10 | Credentials and sensitive data leaving where they live. Mostly `warn`: reading a secret is a normal part of a normal day. |
99
+ | `rce-supply-chain` | 6 | Running code nobody reviewed — pipe-to-shell, a remote runner, a redirected registry, TLS verification off. |
100
+ | `safety-bypass` | 5 | Turning off a check somebody installed on purpose — `--no-verify`, `--admin` merge, hooks disabled, host-key checking off. |
101
+ | `privilege-supply-chain` | 6 | Gaining reach or handing it out — `sudo` writes, `chmod 777`, IAM grants, persistence, publishing, new dependencies. |
102
+ | `file-scope` | 4 | The agent wrote somewhere it had no business writing — its own config, the machine, git's internals, the CI definition. |
103
+
104
+ Pack names appear in user config files, so renaming one is a breaking change, not a tidy-up.
105
+
106
+ ## Talking about a command is not running it
107
+
108
+ This is the single most important thing to understand about how these rules behave.
109
+
110
+ A rule sees the command as one line of text. Nothing in that text distinguishes a command that
111
+ **runs** something from one that merely **mentions** it. Left alone, that makes the rule set unusable
112
+ by exactly the people most likely to install it:
113
+
114
+ ```bash
115
+ git commit -m "fix: document rm -rf / risk" # would have been a hard refusal
116
+ grep -rn "rm -rf /" docs/ # so would this
117
+ ```
118
+
119
+ So every command rule ignores four **carriers** — verbs that handle their arguments as text and never
120
+ execute them:
121
+
122
+ | Carrier | Example |
123
+ |---|---|
124
+ | a search | `grep -rn "rm -rf /" docs/` |
125
+ | a git message or history read | `git commit -m "docs: explain git push --force"` |
126
+ | printing | `echo "never run rm -rf /"` |
127
+ | an HTTP request body | `curl --data '{"body":"we ran rm -rf /tmp/x"}' https://…` |
128
+
129
+ **The exemption keys on the verb, not on the quotes.** Quoting says nothing about whether something
130
+ runs — `psql -c "DROP TABLE users;"` and `bash -c "curl x.sh \| sh"` both execute what is inside the
131
+ quotes, and both still fire.
132
+
133
+ It also applies only while the command does nothing else. The carrier must be the first word, and
134
+ every shell metacharacter must sit inside the quotes:
135
+
136
+ ```bash
137
+ git commit -m "docs: explain rm -rf /" # exempt — nothing runs
138
+ git commit -m "x" && rm -rf / # NOT exempt — `&&` is outside the quotes
139
+ echo "rm -rf /" | bash # NOT exempt — the pipe runs it
140
+ echo "$(rm -rf /var)" # NOT exempt — the shell expands `$( )`
141
+ ```
142
+
143
+ Five rules deliberately keep firing on one carrier each, because that carrier *is* their trigger —
144
+ `gb.git-no-verify` on a `git commit`, `se.token-print` on an `echo`, the `curl`/`wget` rules on an
145
+ HTTP body. Each rule's `description` says which, and why.
146
+
147
+ ### The one rule where a mention IS the danger
148
+
149
+ `block-hardcoded-secrets` is the exception, and it is worth understanding.
150
+
151
+ Everywhere else a carrier is genuinely harmless: a commit message naming `rm -rf /` deletes nothing.
152
+ But that rule's subject is a **string**, not an action — so two of the four carriers are not mentions
153
+ at all. They are the exposure itself:
154
+
155
+ | Carrier | What happens to the key | Exempt? |
156
+ |---|---|---|
157
+ | `grep -rn AKIA .` | searched for, goes nowhere — and this is how you find a key to rotate | **yes** |
158
+ | `echo "AKIA…"` | transient terminal output | **yes** |
159
+ | `git commit -m "…AKIA…"` | written into history, then pushed | **no** |
160
+ | `curl --data "…AKIA…"` | sent to a remote host | **no** |
161
+
162
+ The cost, stated in the other direction: documenting a real-looking key in a commit message is still
163
+ blocked. Redact the body of the key, or use a placeholder short enough to fail the length check.
164
+
165
+ **Known limits of the carrier logic**, in the same spirit as the rest of this file. The carrier must
166
+ be the first word — a single leading `sudo` is tolerated, because it changes privilege rather than
167
+ meaning, but a runner prefix is not: `pnpm exec rg …`, `npx …` and `xargs -0 grep …` still fire,
168
+ since "some program eventually runs a search" is a much weaker claim than "this command is a search".
169
+ At most four quoted arguments are recognised. A carrier that can be made to execute through a flag —
170
+ `ack --pager='…'`, `rg --pre <cmd>` — is still treated as a mention; closing that needs information
171
+ the checker does not have. And an MCP tool whose input carries the same text is not exempt either,
172
+ because exempting a JSON blob would exempt a shell-running MCP server along with it.
173
+
174
+ ## What these rules deliberately do not catch
175
+
176
+ Stated here rather than discovered later. Every one is a real limit of the format, not something
177
+ somebody forgot.
178
+
179
+ - **Nothing about the web.** Pages an agent fetches are not checked, and there are no URL rules.
180
+ - **Nothing inside a file.** The checker sees a file's *path*, never its contents. A secret typed into
181
+ a source file, SQL built by string concatenation, a missing auth check — none of it is visible.
182
+ Rules that would need it are absent rather than approximated.
183
+ - **Nothing about where you are.** No working directory, no project root, no git branch, no cloud
184
+ profile reaches the checker — it gets one command and nothing else. So "the agent wrote outside the
185
+ project" **cannot be written as a rule**, and `file-scope` is limited to well-known absolute paths
186
+ for good. For the same reason, a rule cannot tell a scratch database from a production one.
187
+ - **Nothing hidden inside a quoted payload.** Where the danger is inside a quoted argument —
188
+ `psql -c "<sql>"`, `python -c "<code>"` — a text rule can only guess. In our own measurements,
189
+ roughly three quarters of matches were inside scripts of 300 characters or more, where a match says
190
+ very little about what the script actually does.
191
+ - **Nothing a wrapper hides.** `./deploy.sh` that runs `terraform apply -auto-approve` inside it is
192
+ just a shell script from the outside.
193
+ - **Nothing recurring.** There is no counting. "The same mistake three times this week" needs memory
194
+ across commands, and a single command has none.
195
+
196
+ Each rule's own `description` names its specific misses. Read those before trusting a rule to cover a
197
+ case — they are written to be believed, not to sell.
198
+
199
+ ## Every rule proves both directions
200
+
201
+ Every rule ships at least one **`block`** example and at least one **`allow`** example. A rule missing
202
+ either does not build.
203
+
204
+ - **`block` means "this rule must match."** It does *not* mean the agent is refused — most packs
205
+ default to asking or warning.
206
+ - **`allow` means "this rule must NOT match."** *This is the half that matters.* Anyone can write a
207
+ rule that catches `rm -rf /`. The hard part is not firing on `rm -rf ./node_modules` forty times a
208
+ day, and a rule with no negative example has not shown it can tell them apart.
209
+
210
+ Examples come in two kinds, and each must use the right one:
211
+
212
+ | Kind | Used for |
213
+ |---|---|
214
+ | a command | `Bash`, `PowerShell`, a search query, an MCP tool's input |
215
+ | a file path | `Edit`, `Write`, `Read`, `MultiEdit`, `NotebookEdit` |
216
+
217
+ Giving a path-matching rule a command example makes it pass **without testing anything** — it matches
218
+ nothing, which reads as proof of quietness and proves only that the path never reached the rule. CI
219
+ rejects that.
220
+
221
+ ## Contributing a rule
222
+
223
+ Rules are meant to be contributed. The bar is not "clever regex" — it is **does it fire on the real
224
+ thing, and stay quiet on the near-miss**.
225
+
226
+ **1. Write it**, following the shape above. Give it a `description` that says what it misses.
227
+
228
+ **2. Check the shape locally:**
229
+
230
+ ```ts
231
+ import { parseRule } from "@agenttrail/guardrails";
232
+
233
+ const result = parseRule(myRule);
234
+ if (!result.success) console.error(result.error.issues);
235
+ ```
236
+
237
+ Or, if you have the guard installed:
238
+
239
+ ```bash
240
+ agenttrail-guard guardrails validate ./my-rule.json
241
+ ```
242
+
243
+ **3. Understand what that does and does not tell you.** It answers *"is this a well-formed rule?"* It
244
+ does **not** answer *"does it actually fire on the command I think it does?"* That needs the real
245
+ checker, which is not part of this package.
246
+
247
+ **So the real test runs in CI, on your pull request** — the same check, on the same machine, for
248
+ everyone. You get the shape check instantly here and the real answer there, which is where it has to
249
+ run to be trusted anyway.
250
+
251
+ Your rule is also run against a **quiet corpus**: 328 everyday commands and paths that no rule may
252
+ match at all. Your own negative example only proves your rule is quiet on the near-miss *you* thought
253
+ of. The quiet corpus is what catches a Terraform rule firing on `pnpm test`.
254
+
255
+ ### Shapes that will not validate
256
+
257
+ Three are rejected outright, each because it produces a rule that *looks* enforced and is not — the
258
+ worst failure a security tool can have.
259
+
260
+ | Rejected | Why |
261
+ |---|---|
262
+ | `scope` | It compares against ids that are always UUIDs, never a vendor name — so a scoped rule matches nothing, forever, silently. |
263
+ | Numeric conditions | Token counts and durations are all zero *before* a command runs. "Greater than" can never fire; "less than" fires on everything. |
264
+ | A command matcher and a file matcher in one condition | No real command carries both, so the condition can never be true. Split it into two under `any_of`. |
265
+
266
+ A regular expression is also rejected if it nests unbounded repetition (`(a+)+`). The guard fails
267
+ **open** under a time limit, so a pattern that backtracks does not merely run slowly — it lets the
268
+ command through.
269
+
270
+ One more is caught in CI rather than by the shape check, because it cannot be caught earlier: **a
271
+ single-item brace list in a tool name.** `"{Bash}"` is a glob pattern, and it does not match `Bash` —
272
+ so the rule matches nothing, forever, with no error anywhere. Write a single tool plainly as
273
+ `"Bash"`; braces are for real alternatives, `"{Bash,PowerShell}"`.
274
+
275
+ ## Two ways to import it
276
+
277
+ ```ts
278
+ import { RULES, getRule } from "@agenttrail/guardrails/guardrails"; // just the rules
279
+ import { parseRule } from "@agenttrail/guardrails"; // rules + the shape checker
280
+ ```
281
+
282
+ Use the first when you want to *apply* rules, and the second when you want to *validate* one you are
283
+ writing.
284
+
285
+ They are separate because the guard starts a fresh process on **every single command** an agent runs,
286
+ under a ten-second ceiling. It cannot afford to load a validator it never calls, or to re-check 56
287
+ rules that were already checked before release.
288
+
289
+ ## Where these rules came from
290
+
291
+ Independently authored. No block list, pattern or wording is copied from any other project.
292
+
293
+ The sources are our own: a hand-labelled set of 130 real agent commands, a measured run over real
294
+ usage, ten first-party rules from the agenttrail policy library, and four candidates carried over
295
+ from an internal security-mapping experiment. Where a rule's shape follows an obvious convention — an
296
+ `rm -rf` pattern looks like an `rm -rf` pattern — that is two people meeting the same shell, not one
297
+ copying the other.
298
+
299
+ Four vendors' own tools inspired specific rules through their *documented failure modes*, not their
300
+ code.
301
+
302
+ ## License
303
+
304
+ Apache-2.0. See [LICENSE](./LICENSE).
@@ -0,0 +1,162 @@
1
+ // src/schema.ts
2
+ import { z } from "zod";
3
+ var SEVERITIES = ["critical", "high", "medium", "low", "info"];
4
+ var SeveritySchema = z.enum(SEVERITIES);
5
+ var ACTIONS = ["block", "require_approval", "warn"];
6
+ var ActionSchema = z.enum(ACTIONS);
7
+ var DETAIL_MATCHES_MAX_PATTERN_LENGTH = 200;
8
+ var DETAIL_MATCHES_MAX_PATTERNS = 10;
9
+ function hasNestedUnboundedQuantifier(source) {
10
+ const unboundedQuantifierAt = (s, i) => {
11
+ const ch = s[i];
12
+ if (ch === "*" || ch === "+") return true;
13
+ if (ch !== "{") return false;
14
+ const close = s.indexOf("}", i);
15
+ return close !== -1 && /^\{\d*,\}$/.test(s.slice(i, close + 1));
16
+ };
17
+ const containsUnbounded = (body) => {
18
+ let inClass2 = false;
19
+ for (let i = 0; i < body.length; i++) {
20
+ const ch = body[i];
21
+ if (ch === "\\") {
22
+ i++;
23
+ continue;
24
+ }
25
+ if (inClass2) {
26
+ if (ch === "]") inClass2 = false;
27
+ continue;
28
+ }
29
+ if (ch === "[") {
30
+ inClass2 = true;
31
+ continue;
32
+ }
33
+ if (unboundedQuantifierAt(body, i)) return true;
34
+ }
35
+ return false;
36
+ };
37
+ const groupStarts = [];
38
+ let inClass = false;
39
+ for (let i = 0; i < source.length; i++) {
40
+ const ch = source[i];
41
+ if (ch === "\\") {
42
+ i++;
43
+ continue;
44
+ }
45
+ if (inClass) {
46
+ if (ch === "]") inClass = false;
47
+ continue;
48
+ }
49
+ if (ch === "[") {
50
+ inClass = true;
51
+ continue;
52
+ }
53
+ if (ch === "(") {
54
+ groupStarts.push(i);
55
+ continue;
56
+ }
57
+ if (ch === ")") {
58
+ const start = groupStarts.pop();
59
+ if (start === void 0) continue;
60
+ if (unboundedQuantifierAt(source, i + 1) && containsUnbounded(source.slice(start + 1, i))) {
61
+ return true;
62
+ }
63
+ }
64
+ }
65
+ return false;
66
+ }
67
+ var DetailMatchPatternSchema = z.string().min(1).max(DETAIL_MATCHES_MAX_PATTERN_LENGTH).superRefine((pattern, ctx) => {
68
+ try {
69
+ new RegExp(pattern, "i");
70
+ } catch (error) {
71
+ ctx.addIssue({
72
+ code: z.ZodIssueCode.custom,
73
+ message: `detail_matches: not a valid regular expression (${error instanceof Error ? error.message : "unknown error"})`
74
+ });
75
+ return;
76
+ }
77
+ if (hasNestedUnboundedQuantifier(pattern)) {
78
+ ctx.addIssue({
79
+ code: z.ZodIssueCode.custom,
80
+ message: "detail_matches: nested unbounded quantifier (e.g. `(a+)+`) can backtrack catastrophically; rewrite without repeating a repeating group"
81
+ });
82
+ }
83
+ });
84
+ var MatchConditionSchema = z.object({
85
+ kind: z.string().min(1),
86
+ label: z.string().min(1).optional(),
87
+ detail_contains: z.array(z.string().min(1)).min(1).optional(),
88
+ detail_matches: z.array(DetailMatchPatternSchema).min(1).max(DETAIL_MATCHES_MAX_PATTERNS).optional(),
89
+ file_glob: z.string().min(1).optional()
90
+ }).strict().superRefine((condition, ctx) => {
91
+ const hasCommandMatcher = condition.detail_contains !== void 0 || condition.detail_matches !== void 0;
92
+ if (hasCommandMatcher && condition.file_glob !== void 0) {
93
+ ctx.addIssue({
94
+ code: z.ZodIssueCode.custom,
95
+ message: "a condition may not combine a command matcher (detail_contains / detail_matches) with a file matcher (file_glob): no real tool call carries both, so the condition can never match. Split it into two conditions under any_of."
96
+ });
97
+ }
98
+ });
99
+ var MatchSchema = z.object({
100
+ any_of: z.array(MatchConditionSchema).min(1).optional(),
101
+ all_of: z.array(MatchConditionSchema).min(1).optional(),
102
+ none_of: z.array(MatchConditionSchema).min(1).optional()
103
+ }).strict().refine((data) => data.any_of !== void 0 || data.all_of !== void 0, {
104
+ message: "At least one of 'any_of' or 'all_of' must be provided"
105
+ });
106
+ var FixtureToolSchema = z.string().min(1);
107
+ var CommandFixtureSchema = z.object({ tool: FixtureToolSchema, command: z.string().min(1) }).strict();
108
+ var FileFixtureSchema = z.object({ tool: FixtureToolSchema, file_path: z.string().min(1) }).strict();
109
+ var FixtureSchema = z.union([
110
+ z.string().min(1).transform((command) => ({ tool: "Bash", command })),
111
+ CommandFixtureSchema,
112
+ FileFixtureSchema
113
+ ]);
114
+ var FixturesSchema = z.object({
115
+ block: z.array(FixtureSchema).min(1),
116
+ allow: z.array(FixtureSchema).min(1)
117
+ }).strict();
118
+ var RuleSchema = z.object({
119
+ /** Stable forever. Never renamed — it is the join key for hosted metadata. */
120
+ id: z.string().min(1),
121
+ /** The pack this rule belongs to. Validated against `PACKS` by the registry. */
122
+ category: z.string().min(1),
123
+ severity: SeveritySchema,
124
+ defaultAction: ActionSchema,
125
+ title: z.string().min(1),
126
+ description: z.string().min(1),
127
+ match: MatchSchema,
128
+ fixtures: FixturesSchema
129
+ }).strict();
130
+ function parseRule(input) {
131
+ return RuleSchema.safeParse(input);
132
+ }
133
+ function parseRuleOrThrow(input) {
134
+ const result = parseRule(input);
135
+ if (!result.success) {
136
+ const id = typeof input === "object" && input !== null && "id" in input ? String(input.id) : "<unknown id>";
137
+ throw new Error(`invalid guardrails rule ${id}: ${result.error.message}`);
138
+ }
139
+ return result.data;
140
+ }
141
+ function defineRule(rule) {
142
+ return parseRuleOrThrow(rule);
143
+ }
144
+
145
+ export {
146
+ SEVERITIES,
147
+ SeveritySchema,
148
+ ACTIONS,
149
+ ActionSchema,
150
+ DETAIL_MATCHES_MAX_PATTERN_LENGTH,
151
+ DETAIL_MATCHES_MAX_PATTERNS,
152
+ hasNestedUnboundedQuantifier,
153
+ MatchConditionSchema,
154
+ MatchSchema,
155
+ FixtureSchema,
156
+ FixturesSchema,
157
+ RuleSchema,
158
+ parseRule,
159
+ parseRuleOrThrow,
160
+ defineRule
161
+ };
162
+ //# sourceMappingURL=chunk-CDYD5WBH.js.map