> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_09_permission_control_system/9.2_permission_evaluation_engine.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 9.2 Permission Evaluation Engine

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generation Date**: 2026-02-17

***

In the previous section, we examined the data structures of the permission model -- Rule and Ruleset. This section dives into the core logic of the permission evaluation engine: when an Agent attempts to perform an operation that requires permission, how does the system find a matching rule from the Ruleset and make a decision?

## 9.2.1 Implementation of PermissionNext.evaluate()

`evaluate()` is the core function of the permission system, responsible for finding the best-matching rule for a specific permission request:

```typescript
export function evaluate(
  permission: string,    // Permission type (e.g., "bash")
  pattern: string,       // Matching pattern (e.g., "ls -la")
  ...rulesets: Ruleset[]  // One or more rulesets
): Rule {
  const merged = merge(...rulesets)  // Merge all rulesets
  const match = merged.findLast(
    (rule) =>
      Wildcard.match(permission, rule.permission) &&
      Wildcard.match(pattern, rule.pattern),
  )
  return match ?? { action: "ask", permission, pattern: "*" }
}
```

The logic of this function can be broken down into three steps:

### Step 1: Merge Rulesets

```typescript
const merged = merge(...rulesets)
// merge is just rulesets.flat(), concatenating multiple arrays into one
```

### Step 2: Search Backward for a Match

```typescript
const match = merged.findLast(
  (rule) =>
    Wildcard.match(permission, rule.permission) &&
    Wildcard.match(pattern, rule.pattern),
)
```

`findLast()` is the key -- it searches from the **end of the array** for the first rule that simultaneously satisfies both conditions:

1. The rule's `permission` field matches the requested permission type via wildcard matching
2. The rule's `pattern` field matches the requested pattern via wildcard matching

> **Extended Explanation: Array.prototype.findLast()**
>
> `findLast()` is an array method introduced in the ES2023 standard. It has the same functionality as `find()` but searches in the opposite direction -- from the end of the array toward the beginning. In OpenCode's permission system, this means rules added later have higher priority, naturally implementing "last-writer-wins" override semantics.

### Step 3: Default Fallback

```typescript
return match ?? { action: "ask", permission, pattern: "*" }
```

If no rule matches, the default return is `ask` -- meaning **in the absence of explicit configuration, all sensitive operations will prompt the user**. This embodies the "security-first" design philosophy.

### Evaluation Examples

Suppose we have the following merged Ruleset:

```typescript
const ruleset = [
  // Agent default permissions (added first, lower priority)
  { permission: "*",    pattern: "*",      action: "allow" },
  { permission: "read", pattern: "*.env",  action: "deny"  },
  { permission: "doom_loop", pattern: "*", action: "ask"   },
  // User-configured permissions (added later, higher priority)
  { permission: "bash", pattern: "rm *",   action: "deny"  },
  { permission: "bash", pattern: "ls *",   action: "allow" },
]
```

Evaluation results:

| Request                                | Matched Rule      | Result                                      |
| -------------------------------------- | ----------------- | ------------------------------------------- |
| `evaluate("bash", "ls -la")`           | `bash` / `ls *`   | **allow**                                   |
| `evaluate("bash", "rm -rf /")`         | `bash` / `rm *`   | **deny**                                    |
| `evaluate("bash", "curl https://...")` | `*` / `*`         | **allow** (matches the first wildcard rule) |
| `evaluate("read", ".env")`             | `read` / `*.env`  | **deny**                                    |
| `evaluate("doom_loop", "bash")`        | `doom_loop` / `*` | **ask**                                     |
| `evaluate("unknown", "anything")`      | `*` / `*`         | **allow**                                   |

## 9.2.2 Wildcard Pattern Matching (util/wildcard.ts)

The core of permission evaluation relies on Wildcard pattern matching. OpenCode implements a concise yet fully functional wildcard matcher in `util/wildcard.ts`:

```typescript
export namespace Wildcard {
  export function match(str: string, pattern: string) {
    let escaped = pattern
      .replace(/[.+^${}()|[\]\\]/g, "\\$&")  // Escape regex special characters
      .replace(/\*/g, ".*")                    // * becomes .* (match any characters)
      .replace(/\?/g, ".")                     // ? becomes . (match a single character)

    // Special handling: "ls *" can match both "ls" and "ls -la"
    if (escaped.endsWith(" .*")) {
      escaped = escaped.slice(0, -3) + "( .*)?"
    }

    return new RegExp("^" + escaped + "$", "s").test(str)
  }
}
```

This implementation works by converting wildcard patterns into regular expressions:

1. **Escape special characters**: Escapes regex metacharacters like `.`, `+`, `^`, etc., to prevent them from being interpreted as regex syntax.
2. **Wildcard conversion**:
   * `*` -> `.*` (matches zero or more of any character)
   * `?` -> `.` (matches exactly one of any character)
3. **Trailing space + wildcard optimization**: If the pattern ends with `" *"` (e.g., `"ls *"`), it is converted to `"( .*)?"` making it optional -- meaning `"ls *"` can match both `"ls"` and `"ls -la"`.

Matching examples:

| Pattern | Input              | Result                                  |
| ------- | ------------------ | --------------------------------------- |
| `*`     | Any string         | Matches                                 |
| `bash`  | `"bash"`           | Matches                                 |
| `bash`  | `"read"`           | No match                                |
| `*.env` | `".env"`           | Matches                                 |
| `*.env` | `"production.env"` | Matches                                 |
| `ls *`  | `"ls"`             | Matches (trailing wildcard is optional) |
| `ls *`  | `"ls -la"`         | Matches                                 |
| `rm *`  | `"rm -rf /"`       | Matches                                 |
| `src/*` | `"src/index.ts"`   | Matches                                 |

### Structured Wildcard Matching

`Wildcard` also provides two advanced matching functions:

```typescript
// Find the last matching value in a Record (sorted by key length in ascending order)
export function all(input: string, patterns: Record<string, any>) {
  const sorted = pipe(
    patterns, Object.entries,
    sortBy([([key]) => key.length, "asc"], [([key]) => key, "asc"])
  )
  let result = undefined
  for (const [pattern, value] of sorted) {
    if (match(input, pattern)) {
      result = value  // Override; the last (longest) match wins
    }
  }
  return result
}
```

`all()` sorts by pattern length and matches sequentially, with the longest matching pattern winning. This implements "most specific rule first" semantics -- for example, `"git commit"` is more specific than `"git *"`.

```typescript
// Structured matching: split a command into head (command name) and tail (arguments)
export function allStructured(
  input: { head: string; tail: string[] },
  patterns: Record<string, any>
) {
  // Split patterns by spaces, match head against the first part, tail against the rest
}
```

`allStructured()` is used for fine-grained command permission matching -- it splits a command into a "verb" (e.g., `git`) and "arguments" (e.g., `checkout main`), performing wildcard matching on each part separately.

## 9.2.3 `~` and `$HOME` Path Expansion

In the `pattern` field of permission rules, users can use `~` or `$HOME` to reference the home directory. The `expand()` function expands these symbols into actual paths during rule parsing:

```typescript
function expand(pattern: string): string {
  if (pattern.startsWith("~/"))    return os.homedir() + pattern.slice(1)
  if (pattern === "~")             return os.homedir()
  if (pattern.startsWith("$HOME/")) return os.homedir() + pattern.slice(5)
  if (pattern.startsWith("$HOME"))  return os.homedir() + pattern.slice(5)
  return pattern
}
```

Expansion examples (assuming home directory is `/home/user`):

| Input Pattern      | Expanded Result                |
| ------------------ | ------------------------------ |
| `~/Documents/*`    | `/home/user/Documents/*`       |
| `~`                | `/home/user`                   |
| `$HOME/.ssh/*`     | `/home/user/.ssh/*`            |
| `$HOME`            | `/home/user`                   |
| `/absolute/path/*` | `/absolute/path/*` (unchanged) |

This expansion occurs in `fromConfig()`, i.e., during the Ruleset construction phase, not during the evaluation phase. This means all patterns are normalized at initial load time, avoiding the performance overhead of path expansion on every evaluation.

***

> **Section Summary**
>
> OpenCode's permission evaluation engine is implemented through the `evaluate()` function, whose core is the `findLast()` backward-search strategy -- rules added later automatically gain higher priority, and the default when nothing matches is `ask`. Wildcard matching is implemented by `Wildcard.match()`, which converts `*` and `?` into regular expressions for pattern matching, with special optional handling for trailing `" *"` patterns. Path patterns support `~` and `$HOME` expansion, which is normalized once during the Ruleset construction phase.
