@operad-io/access-match 0.0.0-stage → 0.0.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yinghai Zhao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,166 @@
1
- # Temporary Holding Version
1
+ # @operad-io/access-match
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The access profile matcher. `match(profile, call)` says whether one tool call
4
+ may run under the `denyPaths`, `denyCommands` and `askCommands` of an access profile
5
+ (`docs/backlog/operad-sandbox.md` decisions 1 and 4,
6
+ `docs/backlog/operad-harness-pi.md` decision 7). Harnesses call it in their
7
+ tool-call hook: pi today, Claude and the command adapter later.
8
+
9
+ ```ts
10
+ match(profile, { tool, input, cwd }):
11
+ | { allow: true }
12
+ | { allow: false, reason, rule? } // refused
13
+ | { allow: false, ask: true, reason, rule, kind: "command" | "path", value, tool? } // asks a person
14
+ ```
15
+
16
+ Precedence: **deny wins over ask, and ask wins over allow.** A call that matches
17
+ `denyCommands` or `denyPaths` anywhere is refused, whatever `askCommands` says,
18
+ and nobody is asked; a call that matches only `askCommands` asks; any other call
19
+ is allowed. An `alwaysAllow` entry lifts an ask for its exact call and cwd; it
20
+ never lifts a deny. A caller that does not know `ask` sees `allow: false` and refuses,
21
+ never passes.
22
+
23
+ The matcher is pure and synchronous and keeps no state between calls. It never
24
+ touches the file system: paths are resolved **lexically** against `cwd`. The
25
+ only outside value it reads is the home directory for `~` (`os.homedir()`, or
26
+ the `home` option). `test/match.test.ts` follows the tables below.
27
+
28
+ ## Profile
29
+
30
+ | field | type | meaning |
31
+ |---|---|---|
32
+ | `denyPaths` | string[], optional | a call that touches a path under one of these is refused |
33
+ | `denyCommands` | string[], optional | a `bash` command part that matches one of these is refused |
34
+ | `askPaths` | string[], optional | paths a write asks about (`~/.zshrc`, `~/.*profile`); `*` stays within one path segment and a path under a match counts. Judged for `write` and `edit`, and for a `bash` redirect (`>`, `>>`) to such a path, which asks with the whole command. Deny wins over it |
35
+ | `readOnly` | boolean, optional | the call's working directory is read-only: a write under it (`write`, `edit`, a `bash` redirect) asks, as if the directory were in `askPaths`. Deny wins over it |
36
+ | `readPaths` | array of paths, optional | directories the agent may read although `denyPaths` covers an ancestor: a read tool (`read`, `grep`, `find`, `ls`) or a `bash` command that only reads may touch a path under one. A write there asks (the entries count as `askPaths`); every other denied path stays denied |
37
+ | `allowMcp` | string[], optional | MCP tools that run without asking, as `<server>.<tool>` or `<server>.*`. The field's presence (even empty) puts MCP tools under the profile: a call with `tool: "mcp"` and `input: { server, tool }` that is not listed counts as a write and asks (`kind: "command"`, value `mcp <server>.<tool>`), per `operad-sandbox.md` decision 9. When the field is absent, MCP tools are not under the profile and are allowed |
38
+ | `askCommands` | string[], optional | rules in the shape of `denyCommands`; a `bash` command part that matches one of these asks a person (`operad-sandbox.md` decisions 1 and 3). Writes to shell profiles are `askPaths` |
39
+
40
+ | `alwaysAllow` | `{ kind: "command" \| "path", value, cwd, tool? }[]`, optional | calls a person answered `allow_always` for. A command entry is the exact command text and cwd; a path entry is the tool, the path and cwd. Such a call is allowed when it would otherwise ask. A deny still wins, and a harness leaves the entries out of a run no person's message started (`operad-sandbox.md` decisions 4, 5, 8 and 11) |
41
+
42
+ | `grants` | `{ waitId, kind: "command" \| "path", value, tool? }[]`, optional | one-time permissions not yet used; see `findGrant` |
43
+
44
+ `findGrant(profile, call)` returns the grant that covers a call, or `undefined`:
45
+ a `command` grant covers a `bash` call whose command equals `value` character
46
+ for character, a `path` grant a call of the one `tool` it names (not another path tool) on the same file; a path grant without a `tool` covers nothing. It is
47
+ pure. The caller must use the grant up (the engine writes `grant_used`) before it
48
+ lets the call run, and match the call as usual when it cannot.
49
+
50
+ Other fields of the access profile (`cwd`, `outside`, `network`) are not read
51
+ here. `readProfile(value)` checks an untrusted object
52
+ and names the field at fault.
53
+
54
+ ## Call
55
+
56
+ | tool | what is checked |
57
+ |---|---|
58
+ | `read`, `write`, `edit` | `input.path` (or `input.file_path`) against `denyPaths` |
59
+ | `grep`, `find`, `ls` | `input.path`, when given, against `denyPaths` |
60
+ | `bash` | `denyCommands` and inline code, then every path-like argument against `denyPaths` |
61
+ | anything else | allowed |
62
+
63
+ A missing or non-string path argument of a checked tool is allowed: the tool
64
+ itself reports that error.
65
+
66
+ ## Splitting a `bash` command
67
+
68
+ Outside quotes the command is split into parts at these operators. Each part
69
+ remembers the operator before it.
70
+
71
+ | operator | note |
72
+ |---|---|
73
+ | `&&`, `\|\|`, `;`, `\|`, `\|&`, `&` | `\|\|` and `&&` are read before `\|` and `&` |
74
+ | newline | a backslash before the newline joins the lines instead |
75
+ | `(` and `)` | read as separators; `$(` is inline code, see below |
76
+
77
+ Quotes: `'…'` keeps everything literal; `"…"` keeps operators literal and
78
+ still lets `\"`, `\\`, `` \` `` and `\$` escape; outside quotes a backslash
79
+ escapes the next character. An operator inside quotes or after a backslash
80
+ does not split. An unterminated quote runs to the end of the command.
81
+
82
+ ## Matching a part against `denyCommands`
83
+
84
+ The words of a part are unquoted. Leading `NAME=value` words are skipped. The
85
+ command name is the first word without its directory (`/bin/rm` is `rm`).
86
+ These wrappers are looked through, and the rule is tried at every level:
87
+ `env`, `command`, `exec`, `nohup`, `time`, `builtin`, `sudo`, `doas`. After a
88
+ wrapper, `NAME=value` words and words starting with `-` are skipped.
89
+
90
+ A rule is a pattern of words; `*` in a word matches any characters.
91
+
92
+ | pattern word | matches |
93
+ |---|---|
94
+ | the first word | the command name, whole (`git`) |
95
+ | a word like `-rf` (one dash, letters) | the union of the single-dash letters of the part's arguments contains every letter, so `-fr`, `-rfv` and `-r -f` all match `-rf` |
96
+ | any other word | an argument of the part equal to it (a trailing `/` ignored, except for `/` itself), in any position, so `git -C x push --force` matches `git push --force*` |
97
+ | `…` or `...` | nothing; it only reads well. It adds no condition |
98
+ | `\|` between words | the rule spans a pipeline: each side matches one part, and the parts follow each other joined by `\|`, so `curl … \| sh` matches `curl x \| sh` and `curl x \| tee y \| sh` does not |
99
+
100
+ The reason is `part "<part>" is refused by denyCommands rule "<rule>"`.
101
+
102
+ `askCommands` rules are matched the same way, after every deny check has passed
103
+ (precedence above). The reason is `part "<part>" matches askCommands rule
104
+ "<rule>"`, and the verdict's `value` is the whole command of the call: that is
105
+ what a person is asked about and what a one-time permission (`findGrant`) covers.
106
+ Inline code (below) asks while `askCommands` is set, with the rule `inline code`:
107
+ what it runs cannot be matched (`operad-sandbox.md` decision 4).
108
+
109
+ ## Inline code
110
+
111
+ Refused whatever the rules say, but only when the profile has at least one
112
+ `denyCommands` rule (an empty profile means no checking). The reason is
113
+ `part "<part>" runs inline code (<form>); it is refused while denyCommands is set`.
114
+
115
+ | form | seen as |
116
+ |---|---|
117
+ | `bash -c`, `sh -c`, `zsh -c`, `dash -c` | the command name and a single-dash argument with the letter `c` (`-lc` too) |
118
+ | `python -c`, `python3 -c` | the command name and a single-dash argument with `c` |
119
+ | `node -e`, `bun -e`, `osascript -e` | the command name and a single-dash argument with `e` |
120
+ | `find … -exec`, `-execdir`, `-ok`, `-okdir` | the command name `find` and such an argument |
121
+ | `xargs` | the command name |
122
+ | `eval` | the command name |
123
+ | `` `…` ``, `$(…)`, `<(…)`, `>(…)` | in the command text outside single quotes (also inside double quotes) |
124
+
125
+ ## Paths
126
+
127
+ For `bash`, every word of every part is a candidate, the command name
128
+ included. A word is path-like when it contains `/` or starts with `~` or `.`.
129
+ Two readings are tried: the word with a leading redirect (`>`, `>>`, `<`,
130
+ `2>`, `&>`) removed, and the text after the first `=` of that word
131
+ (`--out=/x`). Each path-like reading is normalised:
132
+
133
+ | step | rule |
134
+ |---|---|
135
+ | `~` | `~` and `~/…` become the home directory; `~name` is left as it is |
136
+ | relative | joined to `cwd` |
137
+ | `.` and `..` | resolved, so `a/../../x` leaves `cwd`; `..` above `/` stays at `/` |
138
+ | trailing `/` | removed |
139
+
140
+ A `denyPaths` entry is normalised the same way (so `.git/config` means the
141
+ one under `cwd`). A path is refused when it equals an entry or is below it
142
+ (`/a/b` is below `/a`; `/ab` is not). The comparison is case-sensitive. The
143
+ reason is `path "<path>" is under denyPaths entry "<entry>"`, with the path as
144
+ written in the call.
145
+
146
+ ## What it cannot see
147
+
148
+ Lexical means the file system is never asked. These pass:
149
+
150
+ - a symlink, hard link or mount that leads into a denied path;
151
+ - case differences on a case-insensitive disk;
152
+ - shell variables and globs (`$HOME/.ssh`, `~/.s*`), and `~name`;
153
+ - a path built by a program the command starts, or read from a file;
154
+ - paths in a script the agent wrote and then runs.
155
+
156
+ The profile is a guard rail, not a boundary (`operad-sandbox.md` decision 7).
157
+
158
+ ## Shell expansion in bash paths
159
+
160
+ The matcher is a guardrail: where it cannot tell, it asks, and a deny always wins over an ask.
161
+
162
+ **Expansion.** `~`, `$HOME` and `${HOME}` become the matcher's home before a path word, a redirect target or a `cd` target is matched. Any other expansion in a path or `cd` target (`$OTHER`, `${…}`, `$(…)`, backticks, `<(…)`, `$((…))`, `$1`, `$@`, `~user`, a `$'…'` word with escapes) asks. Only words that look like paths (they hold a `/`, or start with `~` or `.`) are judged, so `cat $OTHER` is not.
163
+
164
+ **Directory.** Only a plain top-level `cd <path>` in a chain (`&&`, `||`, `;`, `|`) moves the directory the later relative paths are read against; `<path>` is literal or starts with `~`, `$HOME` or `${HOME}`, and `-L`, `-P` and `--` are skipped. Everything else that can change the directory makes it unknown for the rest of the command, and then every later relative path (or command name with a `/`) asks: brace groups `{ }`, subshells `( )`, `if`, `for`, `while`, `until`, `case`, `select`, functions, `eval`, `source` and `.`, `exec`, the `builtin`, `command` and `env` wrappers, `time`, `trap`, `pushd` and `popd` in any form, `cd -`, `cd` with no operand, a `cd` in a pipeline or the background, a `CDPATH` word, and a `cd` target with an unresolved expansion or a glob.
165
+
166
+ **Globs.** A path word with a glob character (`*`, `?`, `[`, `{`, or an extended glob such as `@(…)`) is judged by the literal text before the first one, not by evaluating the pattern: it is refused when a denied entry starts with that prefix or the prefix starts with a denied entry. A `..` after the glob asks.
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "@operad-io/access-match",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./src/index.ts"
7
+ },
8
+ "dependencies": {
9
+ "@operad-io/engine": "0.0.1"
10
+ },
11
+ "description": "operad: access profiles matched against agent tool calls (in development)",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/operad-io/operad.git",
15
+ "directory": "packages/access-match"
16
+ },
17
+ "license": "MIT",
18
+ "files": [
19
+ "src",
20
+ "README.md",
21
+ "LICENSE"
22
+ ]
23
+ }
package/src/command.ts ADDED
@@ -0,0 +1,301 @@
1
+ /**
2
+ * Splits a `bash` command into parts and matches the parts against
3
+ * `denyCommands` rules. The tables are in `../README.md`.
4
+ */
5
+
6
+ /** One command between operators; `sep` is the operator before it ("" for the first). */
7
+ export interface Part {
8
+ readonly sep: string;
9
+ readonly words: readonly string[];
10
+ readonly text: string;
11
+ }
12
+
13
+ export interface Scan {
14
+ readonly parts: readonly Part[];
15
+ /** The first command or process substitution seen outside single quotes. */
16
+ readonly substitution: string | undefined;
17
+ /** An extended glob (`@(a|b)`, `!(a)`, `+(a)`) was seen outside quotes; the shell may expand it to any path. */
18
+ readonly extglob: boolean;
19
+ /** A `$'…'` word with escapes was seen; its characters are not decoded. */
20
+ readonly ansiC: boolean;
21
+ }
22
+
23
+ const WHITESPACE = new Set([" ", "\t", "\r"]);
24
+
25
+ export function scan(command: string): Scan {
26
+ const parts: Part[] = [];
27
+ let substitution: string | undefined;
28
+ let extglob = false;
29
+ let ansiC = false;
30
+ let words: string[] = [];
31
+ let word: string | undefined;
32
+ let sep = "";
33
+ let start = 0;
34
+
35
+ const endWord = (): void => {
36
+ if (word !== undefined) words.push(word);
37
+ word = undefined;
38
+ };
39
+ const endPart = (end: number, next: string, nextStart: number): void => {
40
+ endWord();
41
+ if (words.length > 0) parts.push({ sep, words, text: command.slice(start, end).trim() });
42
+ words = [];
43
+ sep = next;
44
+ start = nextStart;
45
+ };
46
+ const note = (form: string): void => {
47
+ substitution ??= form;
48
+ };
49
+
50
+ let i = 0;
51
+ while (i < command.length) {
52
+ const ch = command.charAt(i);
53
+ const next = command.charAt(i + 1);
54
+ if (ch === "$" && next === "'") {
55
+ let end = i + 2;
56
+ while (end < command.length && command.charAt(end) !== "'") end += command.charAt(end) === "\\" ? 2 : 1;
57
+ const content = command.slice(i + 2, end);
58
+ if (content.includes("\\")) ansiC = true;
59
+ word = (word ?? "") + content;
60
+ i = end + 1;
61
+ continue;
62
+ }
63
+ if (ch === "'") {
64
+ const close = command.indexOf("'", i + 1);
65
+ const end = close === -1 ? command.length : close;
66
+ word = (word ?? "") + command.slice(i + 1, end);
67
+ i = end + 1;
68
+ continue;
69
+ }
70
+ if (ch === '"') {
71
+ word ??= "";
72
+ i += 1;
73
+ while (i < command.length && command.charAt(i) !== '"') {
74
+ const inner = command.charAt(i);
75
+ if (inner === "\\" && i + 1 < command.length) {
76
+ const escaped = command.charAt(i + 1);
77
+ word += '"\\`$'.includes(escaped) ? escaped : `\\${escaped}`;
78
+ i += 2;
79
+ continue;
80
+ }
81
+ if (inner === "`") note("`");
82
+ if (inner === "$" && command.charAt(i + 1) === "(") note("$(");
83
+ word += inner;
84
+ i += 1;
85
+ }
86
+ i += 1;
87
+ continue;
88
+ }
89
+ if (ch === "\\") {
90
+ if (next === "\n") {
91
+ i += 2;
92
+ continue;
93
+ }
94
+ if (i + 1 < command.length) word = (word ?? "") + next;
95
+ i += 2;
96
+ continue;
97
+ }
98
+ if (ch === "`") {
99
+ note("`");
100
+ word = (word ?? "") + ch;
101
+ i += 1;
102
+ continue;
103
+ }
104
+ if (ch === "$" && next === "(") {
105
+ note("$(");
106
+ word = (word ?? "") + ch;
107
+ i += 1;
108
+ continue;
109
+ }
110
+ if ((ch === "<" || ch === ">") && next === "(") {
111
+ note(`${ch}(`);
112
+ word = (word ?? "") + ch;
113
+ i += 1;
114
+ continue;
115
+ }
116
+ if (ch === "(" && word !== undefined && "@!+?*".includes(word.slice(-1)) && word.length > 0) {
117
+ let depth = 0;
118
+ let end = i;
119
+ for (; end < command.length; end += 1) {
120
+ const c = command.charAt(end);
121
+ if (c === "(") depth += 1;
122
+ if (c === ")" && --depth === 0) break;
123
+ }
124
+ extglob = true;
125
+ word += command.slice(i, end + 1);
126
+ i = end + 1;
127
+ continue;
128
+ }
129
+ if (WHITESPACE.has(ch)) {
130
+ endWord();
131
+ i += 1;
132
+ continue;
133
+ }
134
+ if (ch === "&" && (command.charAt(i - 1) === ">" || command.charAt(i - 1) === "<" || next === ">")) {
135
+ word = (word ?? "") + ch; // 2>&1 and &> are redirections, not operators
136
+ i += 1;
137
+ continue;
138
+ }
139
+ if (ch === "&" && next === "&") {
140
+ endPart(i, "&&", i + 2);
141
+ i += 2;
142
+ continue;
143
+ }
144
+ if (ch === "|" && (next === "|" || next === "&")) {
145
+ endPart(i, `|${next}`, i + 2);
146
+ i += 2;
147
+ continue;
148
+ }
149
+ if (ch === "|" || ch === ";" || ch === "&" || ch === "\n" || ch === "(" || ch === ")") {
150
+ endPart(i, ch === "\n" ? ";" : ch, i + 1);
151
+ i += 1;
152
+ continue;
153
+ }
154
+ word = (word ?? "") + ch;
155
+ i += 1;
156
+ }
157
+ endPart(command.length, "", command.length);
158
+ return { parts, substitution, extglob, ansiC };
159
+ }
160
+
161
+ const WRAPPERS = new Set(["env", "command", "exec", "nohup", "time", "builtin", "sudo", "doas"]);
162
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
163
+
164
+ export function baseName(word: string): string {
165
+ const slash = word.lastIndexOf("/");
166
+ return slash === -1 ? word : word.slice(slash + 1);
167
+ }
168
+
169
+ function skipAssignments(words: readonly string[]): readonly string[] {
170
+ let index = 0;
171
+ while (index < words.length && ASSIGNMENT.test(words.at(index) ?? "")) index += 1;
172
+ return words.slice(index);
173
+ }
174
+
175
+ /** The part's words as the part itself, then after each wrapper in front. */
176
+ export function levels(words: readonly string[]): ReadonlyArray<readonly string[]> {
177
+ const result: Array<readonly string[]> = [];
178
+ let current = skipAssignments(words);
179
+ while (current.length > 0) {
180
+ result.push(current);
181
+ if (!WRAPPERS.has(baseName(current.at(0) ?? ""))) break;
182
+ let rest = current.slice(1);
183
+ for (;;) {
184
+ const first = rest.at(0);
185
+ if (first === undefined || !(first.startsWith("-") || ASSIGNMENT.test(first))) break;
186
+ rest = rest.slice(1);
187
+ }
188
+ current = rest;
189
+ }
190
+ return result;
191
+ }
192
+
193
+ const CLUSTER = /^-[A-Za-z0-9]+$/;
194
+
195
+ function letters(args: readonly string[]): Set<string> {
196
+ const found = new Set<string>();
197
+ for (const arg of args) {
198
+ if (CLUSTER.test(arg)) for (const letter of arg.slice(1)) found.add(letter);
199
+ }
200
+ return found;
201
+ }
202
+
203
+ const SHELLS = new Set(["bash", "sh", "zsh", "dash", "ksh"]);
204
+ const INLINE_E = new Set(["node", "bun", "osascript"]);
205
+ const FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
206
+
207
+ /** The inline-code form a part runs at one wrapper level, or undefined. */
208
+ function inlineForm(words: readonly string[]): string | undefined {
209
+ const name = baseName(words.at(0) ?? "");
210
+ const args = words.slice(1);
211
+ if (SHELLS.has(name) && letters(args).has("c")) return `${name} -c`;
212
+ if (/^python[0-9.]*$/.test(name) && letters(args).has("c")) return `${name} -c`;
213
+ if (INLINE_E.has(name) && letters(args).has("e")) return `${name} -e`;
214
+ if (name === "find") {
215
+ const hit = args.find((arg) => FIND_EXEC.has(arg));
216
+ if (hit !== undefined) return `find ${hit}`;
217
+ }
218
+ if (name === "xargs" || name === "eval") return name;
219
+ return undefined;
220
+ }
221
+
222
+ export function inlineFormOf(part: Part): string | undefined {
223
+ for (const level of levels(part.words)) {
224
+ const form = inlineForm(level);
225
+ if (form !== undefined) return form;
226
+ }
227
+ return undefined;
228
+ }
229
+
230
+ function glob(pattern: string): RegExp {
231
+ const source = pattern
232
+ .split("*")
233
+ .map((piece) => piece.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
234
+ .join(".*");
235
+ return new RegExp(`^${source}$`);
236
+ }
237
+
238
+ interface Segment {
239
+ readonly command: RegExp;
240
+ readonly conditions: readonly string[];
241
+ }
242
+
243
+ export interface Rule {
244
+ readonly text: string;
245
+ readonly segments: readonly Segment[];
246
+ }
247
+
248
+ export function parseRule(text: string): Rule | undefined {
249
+ const segments: Segment[] = [];
250
+ for (const piece of text.split("|")) {
251
+ const words = piece.split(/\s+/).filter((w) => w.length > 0 && w !== "…" && w !== "...");
252
+ const first = words.at(0);
253
+ if (first === undefined) return undefined;
254
+ segments.push({ command: glob(first), conditions: words.slice(1) });
255
+ }
256
+ return { text, segments };
257
+ }
258
+
259
+ function trimSlash(arg: string): string {
260
+ return arg.length > 1 ? arg.replace(/\/+$/, "") || "/" : arg;
261
+ }
262
+
263
+ function segmentMatches(segment: Segment, words: readonly string[]): boolean {
264
+ if (!segment.command.test(baseName(words.at(0) ?? ""))) return false;
265
+ const args = words.slice(1);
266
+ const found = letters(args);
267
+ return segment.conditions.every((condition) => {
268
+ if (CLUSTER.test(condition)) return [...condition.slice(1)].every((letter) => found.has(letter));
269
+ const pattern = glob(condition);
270
+ return args.some((arg) => pattern.test(arg) || pattern.test(trimSlash(arg)));
271
+ });
272
+ }
273
+
274
+ function partMatches(segment: Segment, part: Part): boolean {
275
+ return levels(part.words).some((level) => segmentMatches(segment, level));
276
+ }
277
+
278
+ /** Whether the rule matches the parts starting at `from`. */
279
+ function matchesAt(rule: Rule, parts: readonly Part[], from: number): boolean {
280
+ return rule.segments.every((segment, offset) => {
281
+ const part = parts[from + offset];
282
+ if (part === undefined) return false;
283
+ if (offset > 0 && part.sep !== "|" && part.sep !== "|&") return false;
284
+ return partMatches(segment, part);
285
+ });
286
+ }
287
+
288
+ /** The text of the matched parts for the first rule that matches, or undefined. */
289
+ export function findDenied(
290
+ rules: readonly Rule[],
291
+ parts: readonly Part[],
292
+ ): { readonly text: string; readonly rule: string } | undefined {
293
+ for (let from = 0; from < parts.length; from += 1) {
294
+ for (const rule of rules) {
295
+ if (!matchesAt(rule, parts, from)) continue;
296
+ const matched = parts.slice(from, from + rule.segments.length);
297
+ return { text: matched.map((p) => p.text).join(" | "), rule: rule.text };
298
+ }
299
+ }
300
+ return undefined;
301
+ }