@noppu-labs/opencode-permission-reviewer 2.4.2 → 3.1.0

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +174 -1
  2. package/LICENSE +21 -201
  3. package/LICENSE-APACHE +201 -0
  4. package/MIGRATION.md +2 -1
  5. package/NOTICE +14 -6
  6. package/README.md +109 -787
  7. package/SECURITY.md +41 -22
  8. package/dist/explain.d.ts +3 -4
  9. package/dist/explain.js +9708 -4298
  10. package/dist/index.d.ts +1096 -987
  11. package/dist/index.js +18646 -10575
  12. package/dist/rpc.d.ts +38 -38
  13. package/dist/rpc.js +30 -18
  14. package/dist/tui/config/jsonc.ts +71 -63
  15. package/dist/tui/config/layer-read.ts +120 -0
  16. package/dist/tui/config/loader.ts +73 -512
  17. package/dist/tui/config/risk-policy-clamp.ts +80 -0
  18. package/dist/tui/config/trust-boundary-keys.ts +102 -0
  19. package/dist/tui/config/trust-boundary.ts +148 -0
  20. package/dist/tui/config/trusted-degradation.ts +97 -0
  21. package/dist/tui/config-fields.ts +75 -0
  22. package/dist/tui/config-knobs.ts +119 -0
  23. package/dist/tui/config-policy-rules.ts +86 -0
  24. package/dist/tui/config-risk-policy.ts +59 -0
  25. package/dist/tui/config-rule-condition.ts +150 -0
  26. package/dist/tui/config.ts +72 -431
  27. package/dist/tui/descriptor-io.ts +42 -0
  28. package/dist/tui/failure-kind.ts +28 -0
  29. package/dist/tui/is-record.ts +13 -0
  30. package/dist/tui/opencode/event-normalizer.ts +41 -31
  31. package/dist/tui/reviewer-model.ts +87 -0
  32. package/dist/tui/system-one-routing.ts +110 -0
  33. package/dist/tui/tui.tsx +97 -99
  34. package/dist/tui/types.ts +206 -596
  35. package/dist/tui/ui/action-fit.ts +161 -0
  36. package/dist/tui/ui/action-spans.tsx +60 -0
  37. package/dist/tui/ui/attribution.ts +113 -0
  38. package/dist/tui/ui/components.tsx +69 -137
  39. package/dist/tui/ui/config-notices.ts +137 -0
  40. package/dist/tui/ui/fit-parts.ts +76 -0
  41. package/dist/tui/ui/manual-toast.ts +87 -0
  42. package/dist/tui/ui/review-connection.ts +32 -0
  43. package/dist/tui/ui/review-feed.ts +156 -0
  44. package/dist/tui/ui/review-overlay.tsx +111 -0
  45. package/dist/tui/ui/review-result.tsx +74 -0
  46. package/dist/tui/ui/review-store.ts +88 -0
  47. package/dist/tui/ui/review-theme.ts +70 -0
  48. package/dist/tui/ui/rpc.ts +5 -2
  49. package/dist/tui/ui/v1-host.ts +66 -0
  50. package/dist/tui/ui/v2.tsx +82 -220
  51. package/dist/tui/ui-protocol.ts +112 -124
  52. package/dist/tui/ui-state.ts +86 -64
  53. package/dist/tui/ui-status-extras.ts +165 -0
  54. package/dist/tui/ui-status-parse.ts +132 -0
  55. package/dist/tui/ui-text-elide.ts +89 -0
  56. package/package.json +24 -23
  57. package/rpc.js +2 -1
  58. package/server.js +2 -2
  59. package/tui.tsx +2 -1
package/README.md CHANGED
@@ -1,160 +1,92 @@
1
1
  # OpenCode Permission Reviewer
2
2
 
3
- > [!NOTE]
4
- > This is an **unofficial community plugin** for OpenCode. It is not affiliated
5
- > with or endorsed by [Anomaly](https://anoma.ly).
6
-
7
- > [!NOTE]
8
- > This fork of [warc0s/opencode-permission-reviewer](https://github.com/warc0s/opencode-permission-reviewer)
9
- > is published to npm as `@noppu-labs/opencode-permission-reviewer`. It carries fixes
10
- > that are waiting upstream.
11
-
12
- > **A tool-free AI reviewer for every `ask` permission.** It reads the request,
13
- > your policy, and the session context, then **allows, denies with
14
- > feedback, or escalates to you** — so safe actions don't wait for a keystroke,
15
- > and genuinely risky ones still get blocked or surfaced.
16
-
3
+ [![checks](https://img.shields.io/github/actions/workflow/status/noppu-labs/opencode-permission-reviewer/ci.yml?branch=main&label=checks)](https://github.com/noppu-labs/opencode-permission-reviewer/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/@noppu-labs/opencode-permission-reviewer?color=CB3837)](https://www.npmjs.com/package/@noppu-labs/opencode-permission-reviewer)
5
+ [![downloads](https://img.shields.io/npm/dw/@noppu-labs/opencode-permission-reviewer)](https://www.npmjs.com/package/@noppu-labs/opencode-permission-reviewer)
17
6
  [![OpenCode](https://img.shields.io/badge/OpenCode-%E2%89%A51.18.29-6E56CF)](https://opencode.ai)
18
7
  [![Bun](https://img.shields.io/badge/Bun-%E2%89%A51.3.0-000000)](https://bun.sh)
19
- [![npm](https://img.shields.io/npm/v/@noppu-labs/opencode-permission-reviewer?color=CB3837)](https://www.npmjs.com/package/@noppu-labs/opencode-permission-reviewer)
20
- [![Downloads](https://img.shields.io/npm/dw/@noppu-labs/opencode-permission-reviewer)](https://www.npmjs.org/package/@noppu-labs/opencode-permission-reviewer)
21
- [![License](https://img.shields.io/github/license/Warc0s/opencode-permission-reviewer?color=blue)](./LICENSE)
22
- [![Checks](https://img.shields.io/github/actions/workflow/status/Warc0s/opencode-permission-reviewer/ci.yml?branch=main&label=checks)](https://github.com/Warc0s/opencode-permission-reviewer/actions/workflows/ci.yml)
23
- [![Open issues](https://img.shields.io/github/issues/Warc0s/opencode-permission-reviewer?color=555)](https://github.com/Warc0s/opencode-permission-reviewer/issues)
24
-
25
- OpenCode pauses on **every** `ask` permission and waits for a keystroke — even
26
- for safe, routine actions. This plugin adds a Codex-Guardian-style reviewer: a
27
- dedicated, tool-free model backend reads the pending request, bounded
28
- transcript evidence, recovered user intent, and **a tenant policy you control**,
29
- then allows, denies with rationale, or escalates to you.
30
- Actions the reviewer classifies as critical are not auto-approved. Failures do
31
- not become new approvals: they lead to manual review or denial, depending on
32
- the host and configuration.
33
-
34
- - **Preserves your policy** — `allow` continues, `deny` stays blocked; neither
35
- ever reaches the reviewer.
36
- - **Tool-free review**: normal models run in an isolated scratch session with
37
- every tool denied; Jev uses its typed System One API, which exposes no tools
38
- or project runtime.
39
- - **Read-only enrichment** — bounded, sanitized SSH / local-script / Git
40
- evidence for the reviewer; the filesystem is never modified.
41
- - **Auditable** — one JSONL record per review, with remote commands stored as
42
- SHA-256, not plaintext.
43
- - **Optional TUI overlay** — shows review state and gets out of the way of your
44
- native approval controls.
45
-
46
- > **Policy design inspired by [OpenAI Codex Guardian](https://github.com/openai/codex/tree/main/codex-rs/core/src/guardian).**
47
- > The wording and implementation are independent. See [`NOTICE`](./NOTICE).
48
-
49
- ---
50
-
51
- ## Quickstart
52
-
53
- ### Requirements
54
-
55
- - [Bun](https://bun.sh) ≥ 1.3.0 (CI runs 1.3.0 and 1.3.5)
56
- - [OpenCode](https://opencode.ai) V1 `>=1.18.29 <2` (**tested with 1.18.34**), or V2 `>=2.0.3 <3` (**tested with 2.0.21**)
57
- - `git` on `PATH` (only used for read-only Git-state enrichment; missing git
58
- degrades gracefully)
59
- - A model provider configured in OpenCode, exposing a model that follows JSON
60
- schemas reliably, or a Jev API key in the trusted process environment (see
61
- [Choosing the reviewer model](#choosing-the-reviewer-model))
62
- - A permission policy with at least one `ask` rule — **if nothing is `ask`, the
63
- plugin never activates** (everything is already `allow`/`deny`).
64
-
65
- See [Supported versions](#supported-versions) for the full matrix.
66
-
67
- ### Install
68
-
69
- The package is published to **npm**. Install it as a dependency, or clone and
70
- build when you want to run from a checkout:
8
+ [![license](https://img.shields.io/badge/license-MIT%20%2B%20Apache--2.0-blue)](#license)
9
+
10
+ An OpenCode plugin that sends every `ask` permission to a tool-free AI reviewer. The reviewer
11
+ reads the pending request, recent transcript evidence, what you asked for, and a policy you
12
+ control. It then allows the action, denies it with a reason the agent can act on, or escalates
13
+ it to you. Routine actions stop waiting for a keystroke, and risky ones are still blocked or
14
+ brought to you.
15
+
16
+ This is a fork of [warc0s/opencode-permission-reviewer](https://github.com/warc0s/opencode-permission-reviewer),
17
+ published to npm as `@noppu-labs/opencode-permission-reviewer`. It includes changes upstream
18
+ has not released, such as Jev's System One scores in audit records. It is an unofficial community
19
+ plugin, not affiliated with or endorsed by [Anomaly](https://anoma.ly).
20
+
21
+ ## What it does
22
+
23
+ - Leaves your existing policy alone: `allow` rules continue and `deny` rules stay blocked
24
+ without reaching the reviewer.
25
+ - Reviews in isolation. Normal models run in a scratch session with every operational tool
26
+ denied. Jev models use their typed System One API, which exposes no tools or project runtime.
27
+ - Gives the reviewer bounded, sanitized, read-only evidence about SSH commands, local scripts,
28
+ and Git state.
29
+ - Never auto-approves an action the reviewer classifies as critical. Reviewer failures lead to
30
+ manual review or denial, depending on the host and configuration, and never to an approval.
31
+ - Writes one JSONL audit record per review, with remote commands stored as SHA-256 hashes.
32
+ - Shows review progress in an optional TUI overlay that steps aside for OpenCode's own approval
33
+ controls.
34
+ - Runs headless. Reviews happen inside the OpenCode server, so the plugin works with
35
+ `opencode serve`, `opencode run`, and API clients without a TUI. With `escalationMode: "deny"`,
36
+ unattended agents never wait on a human prompt and anything uncertain is rejected with a reason.
37
+ See [Headless use](docs/CONFIGURATION.md#headless-use).
38
+
39
+ ## Requirements
40
+
41
+ - [Bun](https://bun.sh) >= 1.3.0
42
+ - [OpenCode](https://opencode.ai) V1 `>=1.18.29 <2` (tested with 1.18.35) or V2 `>=2.0.3 <3`
43
+ (tested with 2.0.26)
44
+ - `git` on `PATH`, used only for read-only Git enrichment. Without it, the reviewer gets no Git
45
+ snapshot.
46
+ - A reviewer model: either a model configured in OpenCode that follows JSON schemas reliably, or
47
+ a Jev API key in the OpenCode server's environment. See
48
+ [Reviewer models](docs/REVIEWER-MODELS.md).
49
+ - At least one action in your OpenCode permission policy that resolves to `ask`. On V2, an action
50
+ that matches no rule is `ask` by default. If everything is already `allow` or `deny`, the plugin
51
+ never runs.
52
+
53
+ [docs/COMPATIBILITY.md](docs/COMPATIBILITY.md) has the full support matrix.
54
+
55
+ ## Install
71
56
 
72
57
  ```bash
73
- # From npm
74
58
  bun add @noppu-labs/opencode-permission-reviewer # or: npm install @noppu-labs/opencode-permission-reviewer
75
-
76
- # From a checkout (development)
77
- git clone https://github.com/noppu-labs/opencode-permission-reviewer.git
78
- cd opencode-permission-reviewer
79
- bun install && bun run build
80
59
  ```
81
60
 
82
- What ships in `dist/`:
83
-
84
- - **Server** — `main` / `./server` → `dist/index.js` (bundled).
85
- - **TUI overlay** — `./tui` → `dist/tui/tui.tsx` (**raw TSX**, not a JS bundle).
86
- OpenCode's host compiles that entry with its own Solid/OpenTUI pipeline and
87
- rewrites `solid-js` / `@opentui/*` onto the host runtime. A prebundled
88
- `dist/tui.js` loads but **never paints** the overlay.
89
- - **CLI** — `./cli` / `bin` → `dist/explain.js`.
90
-
91
- The CLI can register the plugin for you (`--tui` writes V1 `tui.json` or V2 global `cli.json`;
92
- `--npm` emits an npm package name instead of a path; it never clobbers an
93
- existing entry):
61
+ The CLI can register the plugin for you. `--host auto` detects V1 or V2, `--tui` also registers
62
+ the overlay (V1 `tui.json` or V2 global `cli.json`), and `--npm` writes the package name instead
63
+ of a path. It never overwrites an existing entry.
94
64
 
95
65
  ```bash
96
66
  bunx @noppu-labs/opencode-permission-reviewer init --host auto --npm --tui --yes
97
67
  ```
98
68
 
99
- ### Configure OpenCode V1
69
+ To run from a checkout instead, clone the repository, run `bun install && bun run build`, and
70
+ register the checkout's absolute path.
71
+
72
+ ## Configure
100
73
 
101
- Register the plugin in your `opencode.json` (project or
102
- `~/.config/opencode/opencode.json`). Use an absolute path to a checkout, or the
103
- npm package name after `bun add` / `npm install`:
74
+ Register the plugin.
75
+
76
+ OpenCode V1 (`opencode.json` in the project, or `~/.config/opencode/opencode.json`):
104
77
 
105
78
  ```jsonc
106
79
  // opencode.json
107
80
  {
108
81
  "$schema": "https://opencode.ai/config.json",
109
- "plugin": ["/absolute/path/to/opencode-permission-reviewer"],
110
- // or: "plugin": ["@noppu-labs/opencode-permission-reviewer"],
82
+ "plugin": ["@noppu-labs/opencode-permission-reviewer"],
111
83
  "permission": {
112
84
  "bash": "ask", // at least one ask rule, or the plugin is a no-op
113
85
  },
114
86
  }
115
87
  ```
116
88
 
117
- For the optional TUI overlay, register the plugin in your `tui.json`
118
- (`~/.config/opencode/tui.json`). Both V1 components read the global
119
- `permission-reviewer.jsonc`, so put shared reviewer settings there rather
120
- than repeating them in the two plugin entries. The built-in default is
121
- `openai/gpt-6-luna` at `medium` reasoning. To override it for both, use:
122
-
123
- ```jsonc
124
- // ~/.config/opencode/permission-reviewer.jsonc
125
- { "model": "provider/model", "variant": "medium", "timeoutMs": 120000 }
126
- ```
127
-
128
- ```jsonc
129
- // tui.json
130
- {
131
- "$schema": "https://opencode.ai/tui.json",
132
- "plugin": ["/absolute/path/to/opencode-permission-reviewer"],
133
- }
134
- ```
135
-
136
- **Restart OpenCode fully** after install or rebuild. The host imports the plugin
137
- once at startup; a live session keeps the previous code in memory and will not
138
- show a rebuilt overlay.
139
-
140
- Then ask the agent to run something safe, e.g. `printf hello`. An auto-approved
141
- `ask` resolves itself with `once` and the tool runs normally — **without**
142
- injecting rationale into the agent context. Denials still return a short reason
143
- the agent can act on.
144
-
145
- **Cost note:** every `ask` action makes one reviewer call (up to `timeoutMs`).
146
- Normal models use an extra child session; Jev uses a direct typed request. Your
147
- model spend scales with how much your policy `ask`s. Lower the reasoning
148
- `variant` where supported or raise `confidenceThreshold` to taste.
149
-
150
- ### Configure OpenCode V2
151
-
152
- V2 uses `plugins` with object entries. The same package supplies `setup()` for
153
- the server and a separate TUI adapter. Use `--host v2` to select this format:
154
-
155
- ```bash
156
- bunx @noppu-labs/opencode-permission-reviewer init --host v2 --npm --tui --yes
157
- ```
89
+ OpenCode V2:
158
90
 
159
91
  ```jsonc
160
92
  // opencode.json
@@ -164,680 +96,70 @@ bunx @noppu-labs/opencode-permission-reviewer init --host v2 --npm --tui --yes
164
96
  }
165
97
  ```
166
98
 
167
- The optional interface belongs in the global `cli.json`, not a project
168
- `tui.json`. The installer writes the correct destination. Reviewer settings
169
- belong in the trusted global `permission-reviewer.jsonc`; V2 inline options
170
- of unknown provenance can only tighten security restrictions. The TUI reads
171
- effective settings and review status from the server.
172
-
173
- V2 uses the official authenticated client to manage isolated reviewer sessions
174
- for normal models. It reuses one reviewer location per backend, removes every
175
- MCP server there, including ones other plugins add from code, and checks that
176
- the location has no MCP servers before each review. Jev instead uses its direct
177
- typed API.
178
- The registered service is discovered without starting or stopping it. For an
179
- independent `serve`, configure `OPENCODE_PERMISSION_REVIEWER_HOST_URL` and the
180
- host's `OPENCODE_PASSWORD` in the trusted process environment. An identity check
181
- rejects connections to a different plugin instance. Provider credentials stay
182
- inside OpenCode. See [Migration and rollback](./MIGRATION.md).
183
-
184
- Structured output uses a dedicated schema-validated result tool. All operational
185
- tools remain disabled. `retainReviewSessions: false` removes the auxiliary
186
- session; `true` keeps it for inspection. `reviewBudgetMs` bounds the whole
187
- review; by default it is `2 * timeoutMs + 60000`. Retries consume this budget.
188
-
189
- ## Choosing the reviewer model
190
-
191
- By default the reviewer is a normal OpenCode model invocation with every tool
192
- denied at the session-permission level, so it can be **any model from any
193
- provider you have configured**. Jev models automatically use the typed System
194
- One API instead. For V1, put shared options in the global
195
- `permission-reviewer.jsonc`; both the server and TUI read it. For V2, the
196
- server reads that file and the TUI receives effective settings from the server.
197
- The model options are:
198
-
199
- - **`model`**: in `provider/model` form. Chat models must match a configured
200
- OpenCode provider; supported Jev IDs use the direct System One API below.
201
- - **`variant`**: reasoning effort the model supports (`max`, `high`, `medium`,
202
- `low`, `none`). Passed straight through to OpenCode.
203
- - **`outputFormat`**: how the reviewer returns its decision: `json_schema`
204
- (default; uses OpenCode's structured output, needs provider support) or
205
- `text` (ask the model to emit JSON in plain text and parse it locally). Use
206
- `text` for models that reject the `json_schema` format, e.g.
207
- `opencode-go/deepseek-v4-flash`.
208
- - **`timeoutMs`**: review timeout; keep it in the shared config for V1.
209
-
210
- The default reviewer is **`openai/gpt-6-luna`** (`medium` reasoning). Override
211
- `model` to use any other provider/model you have configured; whichever you pick should follow structured
212
- output reliably. Model mistakes can cause unsupported approvals as well as
213
- unnecessary escalations, so compare both safety errors and format validity.
214
- Higher reasoning variants may cost more or take longer without always improving
215
- the result.
216
-
217
- ### Jev System One reviewer
218
-
219
- Set `model` in the trusted global `~/.config/opencode/permission-reviewer.jsonc`
220
- and put the matching key in the **OpenCode server process environment** before
221
- starting OpenCode. The Jev call uses the provider's System One endpoint directly;
222
- OpenCode's `/connect` credentials and the Command Code CLI login are not read by
223
- this call. The supported routes are:
224
-
225
- | Reviewer `model` | Required environment variable | System One API |
226
- | ------------------------------------------------------ | ----------------------------- | --------------------------------------------------------------------------------------------- |
227
- | `opencode/jev-1.13` (or `opencode/jev-1.13-free`) | `OPENCODE_API_KEY` | [OpenCode Zen](https://opencode.ai/docs/en/zen/#jev) |
228
- | `typesafe-ai/jev-1.13.0` (or `typesafe-ai/jev-latest`) | `TYPESAFE_API_KEY` | [TypeSafe AI](https://docs.typesafe.ai/sdk/javascript) |
229
- | `commandcode/typesafe/jev` | `CMD_API_KEY` | [Command Code Provider API](https://commandcode.ai/docs/provider#decision-models-typesafejev) |
230
-
231
- For **Jev only**, omit `escalationReviewer`:
232
-
233
- ```jsonc
234
- // ~/.config/opencode/permission-reviewer.jsonc
235
- {
236
- "model": "opencode/jev-1.13",
237
- "timeoutMs": 120000,
238
- }
239
- ```
240
-
241
- Replace the `model` with either of the other IDs in the table to use that
242
- provider. Command Code requires an API-enabled plan such as GOAT, Pro, Max,
243
- Team, or Provider; the Go plan has no Provider API access. Use a Command Code
244
- API key from Studio in `CMD_API_KEY`. Jev is a headless decision model there,
245
- so it cannot be selected as an interactive Command Code chat model.
246
-
247
- For **Jev with selective reasoning escalation**, add a chat model already
248
- configured in OpenCode:
249
-
250
- ```jsonc
251
- // ~/.config/opencode/permission-reviewer.jsonc
252
- {
253
- "model": "commandcode/typesafe/jev",
254
- "timeoutMs": 120000,
255
- "systemOneConfidenceThreshold": 0.4,
256
- "systemOneReasoningThreshold": 0.38,
257
- "escalationReviewer": {
258
- "model": "openai/gpt-6-luna",
259
- "variant": "medium",
260
- "outputFormat": "json_schema",
261
- "timeoutMs": 120000,
262
- },
263
- }
264
- ```
265
-
266
- Jev receives typed state and fixed questions, not a chat session, so `variant`
267
- and `outputFormat` do not apply to the primary call. The plugin reconciles its
268
- answers with deterministic confidence and consistency checks. Straightforward
269
- valid decisions are enforced normally, including valid denials. A difficult
270
- `allow` goes to `escalationReviewer` when configured; an explicit `escalate`
271
- goes there only when Jev assigns enough combined probability to `allow` or
272
- `deny` to make a second opinion useful. Clear escalations remain human reviews
273
- instead of paying for another model that is unlikely to resolve them. Without
274
- `escalationReviewer`, final escalations follow `escalationMode` and the failure
275
- settings. Provider failures, timeouts, and invalid responses never invoke the
276
- second model. The built-in default reviewer remains Luna.
277
-
278
- `systemOneConfidenceThreshold` applies to Jev's outcome confidence, not the
279
- lowest confidence among all descriptive fields. Supporting classifications are
280
- used as consistency signals: very weak support restricts an `allow`, incomplete
281
- evidence requires stronger outcome confidence, and material safety signals
282
- always route away from automatic approval. This calibration is separate from
283
- the chat-reviewer `confidenceThreshold`.
284
- `systemOneReasoningThreshold` controls secondary-review traffic for explicit
285
- Jev escalations. Raising it sends fewer cases to the reasoning reviewer; project
286
- configuration may raise this value but cannot lower a trusted threshold.
287
-
288
- ### Reviewer models without structured-output support
289
-
290
- Some models (for example `opencode-go/deepseek-v4-flash`) do not support
291
- OpenCode's `json_schema` structured-output format and fail with a format error
292
- when it is requested. For those, set `"outputFormat": "text"` so the reviewer
293
- asks the model to emit its decision as plain JSON and parses it locally. Set
294
- this option in the trusted global `permission-reviewer.jsonc` for either host:
295
-
296
- ```jsonc
297
- {
298
- "model": "opencode-go/deepseek-v4-flash",
299
- "variant": "high",
300
- "outputFormat": "text",
301
- "timeoutMs": 120000,
302
- }
303
- ```
304
-
305
- Text mode has no host-side schema enforcement: the plugin re-prompts the
306
- reviewer once if the response is unparseable (mirroring the auto-retry that
307
- `json_schema` mode gets from OpenCode). A response that is still invalid is not
308
- auto-approved; it escalates or is denied according to `escalationMode`. Parsing
309
- is deliberately strict and fail-closed: the entire response must be exactly one
310
- JSON object (optionally wrapped in a single Markdown code fence). Prose around
311
- the object, multiple objects, multiple fences, or any other ambiguity prevents
312
- automatic approval: the parser never guesses which candidate the model meant. Every
313
- parsed decision still passes the same strict `parseDecision` validation and
314
- `enforceDecision` invariants (model-classified critical risk is not approved,
315
- etc.), so text
316
- mode cannot approve anything that structured mode would not.
317
-
318
- One caveat applies to any output format: the deterministic gates check the
319
- decision's _consistency_, not its semantic correctness. A reviewer model that
320
- misclassifies an unsafe action as low risk can produce an unsafe `allow` in
321
- either mode, so pick as strong a reviewer model as your budget allows.
322
-
323
- ### All configuration options
324
-
325
- Every option is optional. Numeric/string options are clamped to safe bounds.
326
-
327
- | Option | Default | Bounds / type | Description |
328
- | ------------------------------ | --------------------------------------------------------- | ----------------------------------- | --------------------------------------------------------------------------------------------- |
329
- | `model` | `openai/gpt-6-luna` | `provider/model` | Reviewer model (override with any provider/model) |
330
- | `variant` | `medium` | non-empty string | Reasoning variant passed to OpenCode |
331
- | `outputFormat` | `json_schema` | `json_schema` / `text` | How the reviewer returns its decision (`text` for models without structured output) |
332
- | `escalationReviewer` | unset | trusted object | Optional reasoning reviewer for valid but difficult Jev decisions |
333
- | `timeoutMs` | `120000` | `5000`–`600000` | Review timeout; put shared V1 settings in the global config |
334
- | `confidenceThreshold` | `0.7` | `0.5`–`1` | Minimum confidence to auto-act; below it escalates |
335
- | `systemOneConfidenceThreshold` | `0.4` | `0.3`–`1` | Calibrated Jev outcome-confidence floor; below it escalates |
336
- | `systemOneReasoningThreshold` | `0.38` | `0`–`1` | Combined `allow`/`deny` probability required to send an explicit Jev escalation to reasoning |
337
- | `maxContextChars` | `32000` | `4000`–`200000` | Total transcript evidence budget |
338
- | `maxPartChars` | `8000` | `500`–`50000` | Per-message-part budget |
339
- | `maxEnrichmentChars` | `24000` | `1000`–`100000` | SSH / script / Git enrichment budget |
340
- | `maxIntentChars` | `8000` | `1000`–`50000` | User-intent history budget |
341
- | `transcriptMessages` | `12` | `1`–`100` | Recent messages shown to the reviewer |
342
- | `intentMessages` | `8` | `1`–`50` | Genuine user intents kept |
343
- | `historyMessages` | `200` | `20`–`500` | Operational messages fetched; literal user intent is recovered separately |
344
- | `retainReviewSessions` | `false` | boolean | Keep reviewer child sessions (debug only; see below) |
345
- | `audit` | `true` | boolean | Append one JSONL audit record per review |
346
- | `auditPath` | `~/.local/share/opencode/permission-reviewer-audit.jsonl` | path | Audit file location |
347
- | `policy` | built-in default | string | Full local override of the tenant policy text |
348
- | `debug` | `false` | boolean | Verbose logs to stderr |
349
- | `enforcementMode` | `observe` | `observe` / `enforce` | `enforce` applies declarative policy routes; `observe` audits them only |
350
- | `escalationMode` | `manual` | `manual` / `deny` | How final escalations are disposed (`manual` = human; `deny` = fail-closed reject) |
351
- | `maxSessionDepth` | `8` | `1`–`32` | Parent-session lineage walk depth |
352
- | `maxParentSessions` | `8` | `0`–`32` | Max parent sessions resolved for actor context |
353
- | `actorProfiles` | `{}` | name → profile map | Trusted agent name → profile (`read-only`, `validation`, `workspace`, …) |
354
- | `riskPolicy` | built-in conservative matrix | object | Override `allow` cells per risk level and failure modes (`onInvalidDecision`, …) |
355
- | `repositoryTrust` | `unknown` | `trusted` / `untrusted` / `unknown` | Repository trust level used by the policy engine |
356
- | `policyRules` | `[]` | array | Declarative rules (most-restrictive wins); project rules combine with trusted ones |
357
- | `askDecisions` | `true` | boolean | Show the reviewer what the user answered in agent ask dialogs (scoped authorization evidence) |
358
-
359
- Config is layered: built-in defaults ← trusted global
360
- `~/.config/opencode/permission-reviewer.jsonc` ← untrusted project
361
- `.opencode/permission-reviewer.jsonc` ← unknown-origin inline plugin options.
362
- The project layer crosses a trust boundary: it can only **tighten**
363
- security-sensitive fields, and its hardening survives even when a trusted layer
364
- set the same field. The project layer cannot choose the reviewer `model`,
365
- `escalationReviewer`, `variant`, `outputFormat`, or replace the `policy` text
366
- (these decide where code/context travels and how the
367
- reviewer enforces and reports), cannot redirect `auditPath`, flip
368
- `retainReviewSessions`, `askDecisions`, or `debug`, grant `actorProfiles`, set
369
- `repositoryTrust: "trusted"`, downgrade a global `enforcementMode: "enforce"`,
370
- or relax a trusted `escalationMode: "deny"` / failure-mode deny knob /
371
- `confidenceThreshold` / `systemOneConfidenceThreshold` /
372
- `systemOneReasoningThreshold` / `riskPolicy`. Reviewer resource knobs
373
- (`timeoutMs`, `reviewBudgetMs`, and the context budgets `maxContextChars`,
374
- `maxEnrichmentChars`, `transcriptMessages`, `historyMessages`,
375
- `maxSessionDepth`, and siblings) cannot be set by the project layer at all:
376
- they decide how long a review runs and how much conversation reaches the
377
- provider, which is not a monotonic security trade, so only global
378
- configuration may move them in either direction. Project and inline
379
- values of the wrong type (including `null`) are ignored, never normalized
380
- back to defaults.
381
-
382
- A config file that exists but cannot be honored fails CLOSED on the trusted
383
- side: a malformed or unreadable **global** config, or trusted `policyRules`
384
- dropped by validation, marks the run _degraded_ — reviews still run, but
385
- automatic approval stays off (everything escalates) until the file is fixed,
386
- and the degradation is reported on stderr. A malformed **project** file is
387
- reported and ignored (the untrusted layer adds nothing anyway).
388
-
389
- In declarative `policyRules`, a `when` condition with an unknown key (a typo),
390
- a `false` flag, or an empty object drops the whole rule — a mistyped rule must
391
- never degrade into a universal match. Catch-all rules are spelled explicitly:
392
- omit `when` entirely, or use `"when": { "always": true }` (valid only alone).
393
- When a catch-all comes from the trusted global config it simply matches
394
- everything; project-sourced allow rules are still rejected outright.
395
-
396
- #### Interactive vs autonomous
397
-
398
- | Mode | Config | Behavior |
399
- | --------------------------- | -------------------------- | ----------------------------------------------------------------------- |
400
- | Interactive (default / 1.0) | `escalationMode: "manual"` | Uncertainty escalates to you; OpenCode's native approval UI takes over |
401
- | Autonomous / fail-closed | `escalationMode: "deny"` | Every final escalation becomes a reject with rationale; no human prompt |
402
-
403
- For unattended agents, set fail-closed in **global** config (not in the repo):
99
+ Reviewer settings go in the trusted global `~/.config/opencode/permission-reviewer.jsonc`. The
100
+ default reviewer is `openai/gpt-6-luna` at `medium` reasoning. To change it:
404
101
 
405
102
  ```jsonc
406
103
  // ~/.config/opencode/permission-reviewer.jsonc
407
- {
408
- "escalationMode": "deny",
409
- }
104
+ { "model": "provider/model", "variant": "medium", "timeoutMs": 120000 }
410
105
  ```
411
106
 
412
- Optional fine-grained hardening under interactive mode (only their own cases):
107
+ Restart OpenCode fully after installing or rebuilding, because the host loads plugins once at
108
+ startup. Then ask the agent to run something safe, such as `printf hello`; it should run
109
+ normally. A denied action returns a short reason the agent can act on.
413
110
 
414
- ```jsonc
415
- {
416
- "riskPolicy": {
417
- "onInvalidDecision": "deny", // invalid structured output → reject
418
- "onReviewerFailure": "deny", // timeout / transport failure → reject
419
- },
420
- }
421
- ```
111
+ Every `ask` costs one reviewer call, so model spend grows with how much your policy asks. A
112
+ lower reasoning `variant` or a higher `confidenceThreshold` reduces it.
422
113
 
423
- `escalationMode: "deny"` hardens every escalate path globally. Restrictive
424
- settings can only block more, never relax security.
425
-
426
- `audit` defaults to `true`. Each completed review appends one JSON object to
427
- the audit path, which is created with — and kept at — mode `0600`: a
428
- pre-existing audit file with looser permissions is tightened before it
429
- receives new records (`schemaVersion: 3`): outcome, decision source,
430
- rationale, risk, authorization, confidence, per-phase latency, reviewer model,
431
- optional `reviewerOutcome` / `escalationDisposition` (to distinguish an explicit
432
- deny from fail-closed escalate→deny), optional System One escalation origin,
433
- and a bounded SSH summary. Remote commands
434
- are stored as **SHA-256**, never in clear text. Set `audit: false` to disable.
435
-
436
- When Jev (System One) returns a valid decision, the record also carries
437
- `systemOne` with Jev's own scores, even when a reasoning reviewer made the
438
- final call and the top-level `confidence` and `riskLevel` are that reviewer's.
439
- It holds the model ID the provider reported, the outcome with its
440
- probabilities, the choice and confidence of each supporting classification,
441
- the nine 0–1 safety signals, the consistency checks that failed, and whether
442
- reasoning was recommended. The model ID is capped at 128 characters and
443
- redacted like other free text; everything else is numbers and fixed labels,
444
- never evidence or command text. The field is absent when Jev never ran (a
445
- deterministic route), when its answer was invalid or its call failed, and on
446
- V1 hosts when a manual answer superseded the automatic review.
447
-
448
- ```json
449
- "systemOne": {
450
- "returnedModel": "jev-1.13.0",
451
- "outcome": { "choice": "allow", "confidence": 0.55, "probabilities": { "allow": 0.55, "deny": 0.05, "escalate": 0.4 } },
452
- "supporting": {
453
- "riskLevel": { "choice": "low", "confidence": 0.82 },
454
- "userAuthorization": { "choice": "high", "confidence": 0.77 },
455
- "scopeAlignment": { "choice": "aligned", "confidence": 0.9 },
456
- "evidenceCompleteness": { "choice": "partial", "confidence": 0.61 },
457
- "primaryBasis": { "choice": "authorized_reversible_change", "confidence": 0.58 }
458
- },
459
- "signals": { "materialAuthorization": 0.81, "withinIntentScope": 0.88, "unauthorizedDataLoss": 0.12, "untrustedSensitiveDisclosure": 0.01, "excessiveCredentialAccess": 0.01, "unauthorizedSecurityChange": 0.02, "unauthorizedExternalMutation": 0.03, "essentialEvidenceMissing": 0.27, "absolutePolicyDeny": 0.02 },
460
- "contradictions": ["an allow with incomplete evidence lacks strong outcome confidence"],
461
- "reasoningRecommended": true
462
- }
463
- ```
114
+ [docs/CONFIGURATION.md](docs/CONFIGURATION.md) covers TUI registration, V2 server connections,
115
+ every option, the trust rules between global and project config, unattended (fail-closed) mode,
116
+ and the audit log.
464
117
 
465
- ## What you'll see
118
+ ## How it works
466
119
 
467
- ```text
468
- ✓ Review approved · bash · rm -rf /tmp/scratch-cache
469
- Narrowly scoped temp cleanup; matches user intent.
470
- ```
120
+ A deterministic emergency brake first rejects unmistakable root destruction and direct
121
+ credential export without calling a model. For everything else, the plugin builds bounded
122
+ evidence from the recent transcript, recovered user intent, and read-only enrichment, with
123
+ common credential formats redacted. A tool-free reviewer returns an outcome, risk level,
124
+ authorization level, rationale, and confidence. Invariants in code then decide whether that
125
+ decision can stand: invalid output, low confidence, and risky actions without matching
126
+ authorization escalate instead of being approved.
471
127
 
472
- While reviewing on V2, the optional TUI shows a compact two-line status strip
473
- at the bottom, matching the result strip's placement. It includes an animated
474
- indicator, **Reviewing this permission**, the reviewer model and reasoning
475
- variant, elapsed time, and the action. Long commands are truncated instead of
476
- expanding over the conversation. V1 retains its larger overlay covering the
477
- native approval controls, including **No action needed**.
478
-
479
- Once resolved, both hosts show a compact status strip: one line for the result
480
- and a second for its rationale, with long text truncated. The review keymap is
481
- released immediately; the result stays visible for 5 s. Editor availability
482
- during a pending review depends on the host; the V2 strip is not a keyboard
483
- lock. On a final escalation in interactive mode, the overlay is removed and
484
- OpenCode's native approval controls become available with a **manual review
485
- required** warning. Host interruption, event-stream loss, and fail-closed
486
- settings can instead deny the request. A broken TUI
487
- transport **never changes the safety decision**.
128
+ With Jev as the reviewer and an `escalationReviewer` configured
129
+ ([Reviewer models](docs/REVIEWER-MODELS.md)), Jev can hand a request to that reasoning reviewer,
130
+ and the progress strip says so; the elapsed time keeps counting from the start of the review.
488
131
 
489
- ## How it works
132
+ ![Two progress strips. While Jev reviews: "◐ Reviewing this permission · jev-1.13.0 · system-one", 2.1s. After the hand-off: "◓ Reviewing this permission · gpt-6-luna after Jev's escalation · medium", 7.3s. Both show "bash · $ git push --force-with-lease origin release/2.4".](https://raw.githubusercontent.com/noppu-labs/opencode-permission-reviewer/main/docs/images/handoff-progress.svg)
490
133
 
491
- 1. OpenCode V1 emits `permission.asked` for an `ask`-classified action. V2 calls
492
- the `permission.evaluate` hook; the plugin preserves decisions already made
493
- by the host or other plugins and reviews only requests that remain `ask`.
494
- 2. A deterministic **emergency brake** rejects unmistakable root destruction and
495
- direct credential export before any model call. It is wrapper-aware
496
- (`sudo`, `doas`, `env`, `command`, `nice`, `nohup`, `systemd-run`, `strace`,
497
- `ltrace`, `script -c`, …), including clustered value-taking options
498
- (`sudo -nu root …`), so `sudo rm -rf /`,
499
- `env VAR=x rm -rf /`, `/bin/rm -rf /`, `sh -c 'rm -rf /'`, `ssh host rm -rf /`,
500
- and `busybox rm -rf /` are all caught. A live root glob (`rm -rf /*`) and
501
- redirections onto real block devices (`> /dev/sda`, `tee /dev/sda`) are
502
- treated as root destruction. Wrapper nesting deeper than a fixed
503
- budget (or command lists beyond a fixed size) is not resolved: the brake
504
- stays quiet for what it cannot fully see, the capability analysis is marked
505
- partial, and automatic approval is blocked, escalating to the user instead.
506
- 3. The plugin builds bounded **evidence**: recent transcript, recovered user
507
- intent, and optional read-only enrichment for SSH commands, local
508
- interpreter scripts, and Git state. Intent attribution uses a single origin
509
- rule: synthetic/host-flagged parts are never human intent, and in a
510
- delegated (subagent) session **no** user-role message counts as human
511
- authorization — the initial briefing and every later `task_id` follow-up
512
- are agent-authored and surface only as labeled delegation context.
513
- Recognized common credential formats are redacted from this evidence
514
- (`Bearer`, AWS / GitHub / OpenAI / Anthropic / Slack / Google / Stripe /
515
- GitLab keys, JWTs, private keys, URL userinfo, cookies, and
516
- credential-bearing assignments). Redaction reduces exposure but cannot
517
- prove that every secret format has been detected.
518
- 4. A **tool-free reviewer backend** returns
519
- `{ outcome, risk_level, user_authorization, rationale, confidence }`.
520
- Normal models use schema-validated output or strict text parsing in a scratch
521
- session outside the project. The host therefore cannot prepend repository
522
- instructions, and a wildcard session rule denies every tool, including MCP
523
- tools. If the host refuses isolation, the review fails safe. Jev instead
524
- receives trusted policy and untrusted evidence as typed System One state
525
- plus fixed questions. Its response is reconciled in code; valid difficult
526
- decisions can be delegated to the optional reasoning reviewer, while
527
- provider failures never are.
528
- 5. Decisions are enforced with invariants: **risk classified as critical by the
529
- reviewer is not auto-approved**,
530
- **high risk with low/unknown authorization is escalated**, **medium risk
531
- with unknown authorization is escalated**, low confidence is escalated,
532
- invalid output is escalated, and reviewer errors and timeouts cannot become
533
- approvals. Two
534
- deterministic blocks also apply regardless of model confidence: a degraded
535
- trusted config (see above) and evidence where a material part of the action
536
- itself was elided or truncated — neither can auto-approve. A single
537
- enforcement boundary then disposes every internal `escalate` according to
538
- `escalationMode` (`manual` → human; `deny` → reject with the original reason).
539
- V2 also denies requests invalidated by cancellation, review deadline, or
540
- loss of the host event connection.
541
- 6. V1 approvals reply `once` (never `always`); V2 approvals return `allow` from
542
- the evaluation hook. Both continue **silently** if the host applies the
543
- decision: the
544
- tool output is not annotated, so approval rationale never contaminates the
545
- primary agent context (rationale still lands in audit, TUI, and debug logs).
546
- Denials return a short actionable rationale as tool feedback. A manual reply
547
- that arrives mid-review **supersedes** the automatic one (no double reply).
548
-
549
- By default final reviewer escalations go to **manual review**. With
550
- `escalationMode: "deny"`, they become rejections with reasons instead. V2 host
551
- interruptions and event-stream failures can deny directly in either mode.
552
-
553
- ## Evidence enrichment
554
-
555
- The reviewer never sees the raw filesystem — only bounded, sanitized evidence.
556
- Enrichment is deliberately conservative and **never makes an approval decision
557
- by itself** (one narrow deterministic exception exists for SSH, below).
558
-
559
- - **SSH commands** are parsed into destination, options, remote command,
560
- environment/mutation/secret/stdin signals, and bounded stdin content for the
561
- common `cat script | ssh ... python -` pattern. Sensitive paths,
562
- credential-like literal content, binary files, unresolved shell expressions,
563
- and symlinks escaping approved roots are excluded.
564
- - **Verified remote shell scripts** have an opt-in command form. Stage the exact
565
- script locally inside the workspace or `/tmp/opencode`, then generate the
566
- command rather than hand-writing its hash guard:
567
-
568
- ```bash
569
- bunx @noppu-labs/opencode-permission-reviewer script command --file /tmp/opencode/deploy.sh --host deploy.example
570
- ```
571
-
572
- Ask the agent to execute the printed command. It streams that local file to
573
- the host, checks its SHA-256 there **before** running `bash`, and removes the
574
- remote temporary copy. Add `--port 2222` or `--shell sh` when needed. The
575
- supported command is deliberately exact: extra shell actions, dynamic paths,
576
- or a remote-only script are **not** treated as verified. The local source is
577
- a copy of the intended executable bytes; if the script comes from Git, stage
578
- the blob from a pinned commit locally before generating the command. It is
579
- re-read on each review and must remain regular, text-only, secret-free, and
580
- at most 64 KiB. A changed file fails the remote hash check even if it changes
581
- after permission approval. The plugin never connects to the host to inspect
582
- it.
583
-
584
- The first permission review includes the whole script. If that review is
585
- approved with sufficient evidence and a script analysis, later reviews in
586
- the same conversation can reuse only a compact, in-memory analysis for the
587
- same hash, host, interpreter, and configuration (up to one hour). **Each
588
- command still receives a fresh authorization decision.** A different script,
589
- host, configuration, or expired analysis requires full inspection again. The
590
- audit stores the hash and inspection status, never the script body. When an
591
- opaque or truncated SSH script is rejected, the agent receives guidance to
592
- stage a local copy and generate this form. The CLI and plugin must use the
593
- same installed package version.
594
-
595
- - **Local interpreter commands** (Python, Node, Bun, shell, Ruby, Perl, and
596
- compound commands that first activate an environment) get the same bounded
597
- inspection when they name an explicit script. Inline code, modules, stdin
598
- programs, dynamic paths, and remote-only SSH arguments are not misidentified
599
- as local files.
600
- - **Package scripts** (`bun run`, `npm run`, `pnpm run`, and `yarn run`) include
601
- the selected manifest definition, defined conditional lifecycle hooks, and
602
- bounded literal calls to other local scripts. Inspection never executes
603
- package code. Cycles, unsupported workspace selection, unavailable files,
604
- and expansion limits remain explicit gaps. Running a local script reports
605
- possible network access rather than an observed network operation.
606
- - **Git operations** (`add`, `commit`, `checkout`, `restore`, `rm`, `merge`,
607
- `rebase`, and `stash`) get a
608
- read-only pre-command snapshot: current branch, files already staged before
609
- the command, unstaged/untracked files, planned targets, unresolved
610
- shell-expanded paths, and a bounded numstat for changes that would be
611
- discarded. Snapshots use fixed non-interactive Git queries with locking and
612
- hooks disabled, a two-second timeout, and bounded output. **The repository is
613
- never modified.** Repository-configured conversion filters (`clean`,
614
- `smudge`, `process`) and diff `textconv` drivers are enumerated before every
615
- snapshot and neutralized with config overrides (including dotted names); if
616
- the configuration cannot be fully verified — too many filters, or the config
617
- scan itself fails — the snapshot is withheld rather than risk executing
618
- repository-configured commands. Verification and inspection are still two
619
- distinct moments: a filter configured between them is a residual race the
620
- snapshot does not claim to eliminate.
621
- Merge snapshots identify the in-progress merge index and unresolved paths.
622
- Rebase snapshots describe the literal commit range and its presence in local
623
- remote-tracking refs; those refs may be stale and never prove publication
624
- status. Literal destinations report conservative matches to configured
625
- push/fetch URLs, including equivalent GitHub HTTPS and SSH forms. A match is
626
- destination identity evidence, not authorization or a trust declaration.
627
- Repository or destination overrides that cannot be resolved with the safe
628
- inspection commands make the snapshot unavailable.
629
-
630
- Only regular text files inside the working directory, the worktree, or
631
- `/tmp/opencode` can be included. A `cd` inside the reviewed command can move
632
- the resolution base for relative paths, but it never mints new approved roots:
633
- `cd /outside && python x.py` resolves in `/outside` and stays blocked. Git
634
- state inspection is contained to the same roots: a `cd /other/repo && git …`
635
- or `git -C /other/repo …` yields an explicitly unavailable snapshot instead of
636
- reading an unrelated repository. Missing, blocked, and truncated executable
637
- stdin is explicitly identified so the reviewer fails safe.
638
-
639
- The **only** deterministic SSH preflight rejection is an executable stdin file
640
- that still does not exist after a 100 ms recheck — the primary agent gets an
641
- actionable instruction to create it and retry. Every other SSH case (sensitive,
642
- binary, blocked, or truncated evidence) remains a reviewer decision.
643
-
644
- ## Safety properties
645
-
646
- - Reviews only `ask` requests: V1 handles `permission.asked`, while V2 handles
647
- `permission.evaluate` without replacing an existing host decision.
648
- - **A decision the model labels critical cannot be auto-approved**, even if its
649
- outcome says `allow`. This does not guarantee that every dangerous action is
650
- classified correctly by the model.
651
- - **High-risk actions with low or unknown authorization, and medium-risk
652
- actions with unknown authorization, are deterministically escalated** — the
653
- model cannot auto-approve them by labeling a contradictory combination.
654
- - Invalid, low-confidence, or inconsistent output cannot create an approval.
655
- Final escalations reach the user or are denied according to `escalationMode`;
656
- some V2 host failures deny directly.
657
- - Known common credential formats are redacted from reviewer evidence. Redaction
658
- is defense in depth, not a guarantee that every possible secret is detected.
659
- - Reviewer sessions cannot request permissions recursively; every tool is
660
- denied by a wildcard session permission rule that also covers MCP tools and
661
- takes precedence over agent-config allows.
662
- - The reviewer session runs outside the project directory, so repository
663
- instructions (`AGENTS.md` and project-config `instructions`) are not part of
664
- its system prompt; if the isolated directory cannot be established, the
665
- review cannot auto-approve rather than running with degraded isolation.
666
- - A narrow deterministic emergency brake rejects unmistakable root destruction
667
- (including privilege-prefixed and command-string forms such as
668
- `sudo rm -rf /`, `sh -c 'rm -rf /'`, `ssh host rm -rf /`) and direct
669
- credential-file export before any model call.
670
- - A manual reply that arrives while a review is in flight **supersedes** it: the
671
- reviewer stops without replying or resurrecting a UI state.
672
- - Approvals are silent to the primary agent (no tool-result annotation); denials
673
- return the rationale as feedback. Rationale remains in audit/TUI/debug.
674
- - SSH commands and executable stdin receive bounded, untrusted action
675
- enrichment; enrichment never makes an approval decision on its own.
676
- - Long-session user intent is recovered separately from recent operational
677
- context; later explicit requests supersede conflicting older ones. V2 reads
678
- literal user messages from the persisted message API, including history
679
- before compaction. V1 scans bounded recent-history windows up to 2,000
680
- messages. Both retain the configured intent count and character budget.
681
- Intent appears once in the reviewer prompt; operational reasoning and
682
- duplicate tool evidence are omitted, while attachments and distinct results
683
- remain visible. Long literal intent retains its beginning and end with an
684
- explicit omission marker.
685
- - Synthetic compaction/control messages are excluded from authorization
686
- evidence.
687
- - Audit failures never affect or relax the safety decision.
688
- - UI status messages are versioned, request-scoped, bounded, and transported
689
- through OpenCode's own workspace TUI event channel.
690
-
691
- ### Supply chain
692
-
693
- - **No code runs at install time.** The package declares no lifecycle
694
- scripts, so installing it from npm executes nothing from this repository.
695
- Installing from a Git URL or a local path executes nothing either, and is
696
- not a supported install method: `dist/` is gitignored, so those installs
697
- yield a package without bundles. Use the npm registry; building from source
698
- is an explicit `bun install && bun run build`.
699
- - **The tarball ships no native code.** `@opentui/core` (the host TUI
700
- pipeline's renderer) declares optional platform-specific native packages
701
- (for example `@opentui/core-linux-x64` on Linux) that npm resolves into the
702
- install tree on your machine. Those renderer packages are used by the TUI.
703
- The `@opencode/client` dependency also reaches optional
704
- `@msgpackr-extract/*` native accelerators through `effect` and `msgpackr`;
705
- the consumer install test tracks their platform package names too. The
706
- published tarball itself contains only JavaScript, raw TSX sources, and documentation;
707
- `tests/package-smoke.test.ts` rejects native addons and shared libraries,
708
- `prebuilds/` directories, platform packages, and bundled-dependency payloads
709
- in the ship set, and every release publishes a CycloneDX SBOM of the
710
- published artifact plus npm provenance for it.
711
- - **The direct runtime dependency set is frozen and tested.** Adding a
712
- dependency (native or not) is a reviewed change: the package smoke test
713
- fails until its allowlist is updated in the same commit. The same suite
714
- installs the published tarball in an isolated tree and freezes what a
715
- consumer actually gets: the platform-specific packages under `@opentui`
716
- (rendering only), the optional `@msgpackr-extract` accelerators, the exact
717
- `@babel/core` and `solid-js` versions documented below, and an `npm audit`
718
- gate that fails on any high or critical advisory other than the documented
719
- `seroval` residuals. Root
720
- `overrides` in this repository protect the development tree only; npm never
721
- applies a dependency's overrides to the installing application, which is
722
- why consumer-side guarantees live in tests against the installed tree
723
- itself.
724
- - **Known residual exposure, documented, not fixed.** `@opentui/solid` pins
725
- `@babel/core@7.28.0` exactly (every published 0.5.x does), and
726
- GHSA-4x5r-pxfx-6jf8 (arbitrary file read via a crafted `sourceMappingURL`
727
- comment, low severity) affects `@babel/core <= 7.29.0`. In this package
728
- that copy of babel only compiles the TUI sources we ship in the tarball,
729
- never repository- or attacker-influenced input, so the advisory's
730
- conditions are not met by our usage; it is still reachable in the consumer
731
- tree and therefore tracked: the consumer surveillance test pins the
732
- installed version, and moving off 7.28.0 is a conscious bump (an
733
- `@opentui/solid` release with a fixed pin, or dropping the exact-pin
734
- constraint) together with this note. The development tree overrides Babel to
735
- 7.29.7, but that override cannot reach an npm consumer. Likewise,
736
- `@opentui/solid` peer-pins `solid-js@1.9.12` exactly, whose `seroval`
737
- dependency carries GHSA-p6vx-979v-rg4c and GHSA-jp82-f5mq-hwhp (unsafe
738
- `fromJSON` deserialization, fixed in `solid-js` 1.9.16). `seroval` is only
739
- imported by the SSR renderer `solid-js/web`, which neither this package nor
740
- OpenTUI loads, so the vulnerable code is not reachable at runtime; the
741
- consumer surveillance test pins `solid-js`, asserts that nothing imports
742
- `solid-js/web`, and admits only those two advisories. Separately, `esbuild`
743
- (a build-time dependency here, never shipped) is root-overridden past
744
- GHSA-g7r4-m6w7-qqqr; that override intentionally does not reach consumers
745
- because consumers never install `esbuild` from this package at all.
746
- - **The `effect` runtime stays external.** `@opencode-ai/plugin` resolves
747
- `effect@4.0.0-beta.83` from the host's own dependency chain for OpenCode V1
748
- hosts. It is externalized from our bundles, not shipped or vendored by this
749
- package, and deliberately not pinned or overridden to a different version:
750
- forcing another version could fork the runtime the V1 host shares with every
751
- other plugin.
752
-
753
- ## Supported versions
754
-
755
- | Component | Supported | Notes |
756
- | --------------------- | ------------------ | ---------------------------------------------------------- |
757
- | OpenCode V1 | `>=1.18.29 <2` | Dual object entrypoint; verified with **1.18.34** |
758
- | OpenCode V2 | `>=2.0.3 <3` | Compatibility layer; verified with **2.0.21** |
759
- | `@opencode-ai/plugin` | `>=1.18.29 <2` | Optional V1 peer dependency |
760
- | Bun | `>=1.3.0` | Declared in `engines.bun`; CI runs **1.3.0** and **1.3.5** |
761
- | TUI overlay | OpenCode V1 and V2 | Separate host adapters, shared raw TSX presentation |
762
- | OS | Linux (verified) | Other operating systems require equivalent live validation |
763
-
764
- - **TUI overlay** ships as **raw TSX** (`dist/tui/tui.tsx`). The host compiles
765
- it against its embedded Solid/OpenTUI runtime. A prebundled TUI entry loads
766
- but never paints. The server half does not depend on the overlay.
767
- - **Server half** replies through an isolated transport chosen once at startup:
768
- public SDK reply with feedback `message` → public reply plus a separate
769
- feedback channel → authenticated raw HTTP
770
- (`/permission/{requestID}/reply` via `input.client._client.post`) → **refuse
771
- startup**. On OpenCode 1.18.x the message-bearing reply is only reachable via
772
- the raw transport, so the chain resolves there. That raw field is **not part
773
- of OpenCode's public plugin API** and can change without notice. If startup
774
- fails with _"authenticated SDK transport is unavailable"_, file an issue
775
- rather than downgrading.
776
- - V2 evaluates pending permissions through `permission.evaluate`. `shell`
777
- and `subagent` map to the shared internal `bash` and `task` labels. Input
778
- already marked allow or deny is not elevated or reviewed.
779
- - Full enrichment assumes a Unix-like system (macOS/Linux). On Windows, SSH and
780
- Git enrichment degrade gracefully toward fail-safe manual review.
781
- - **`retainReviewSessions`**: keep it `false` in normal use. Set `true` to retain
782
- isolated reviewer sessions for inspection in either host generation.
783
- - Run `opencode-permission-reviewer doctor` to compare installed versions
784
- against the ranges above.
785
- - A standard OpenCode installation invokes its runtime directly. Custom
786
- profile launchers are also supported when they select a supported runtime
787
- and provide coherent config, data, state, and cache locations. For the
788
- isolated compatibility matrix, point the host variables at the underlying
789
- executable instead of a launcher that overrides the harness environment;
790
- see [`tests/compatibility`](./tests/compatibility/README.md).
791
-
792
- ## Troubleshooting
793
-
794
- | Symptom | Likely cause | Fix |
795
- | --------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
796
- | Every `ask` escalates after a long wait | Reviewer model not found / provider not configured | Check the model ID in the global `permission-reviewer.jsonc` |
797
- | Plugin does nothing | No `ask` rule in the host permission policy | Set a V1 `"bash": "ask"` rule or a V2 shell permission with `effect: "ask"` |
798
- | TUI overlay never appears | Wrong TUI config; stale process; or host without Solid/OpenTUI pipeline | Check V1 `tui.json` or V2 global `cli.json`. The overlay is raw TSX (`dist/tui/tui.tsx`); a prebundled `dist/tui.js` does not render. Fully restart OpenCode after rebuilds |
799
- | Startup error: "authenticated SDK transport…" | OpenCode V1 outside `>=1.18.29 <2`, or an SDK change that hides the raw transport | Upgrade OpenCode and `@opencode-ai/plugin` into the supported range; report the version in an issue |
800
- | Reviewer host connection unavailable | Independent V2 server without a registered endpoint | Configure the trusted server URL and authentication, then restart |
801
- | Reviews always time out | `timeoutMs` too low for the model | Raise `timeoutMs` (up to 600000) |
802
- | `GIT_STATE_ANALYSIS` shows `spawn git ENOENT` | `git` not on `PATH` | Install `git`; Git enrichment degrades safely until then |
803
- | Want a version check | Host/SDK outside the supported range | Run `opencode --version` and `opencode-permission-reviewer doctor` |
804
- | Want to turn it off | - | Remove the plugin from the host config and, if installed, V1 `tui.json` or V2 global `cli.json` |
805
-
806
- Enable `"debug": true` for verbose stderr logs while investigating. TUI load
807
- errors (`[tui.plugin] …`) are printed on the **TUI process console**, not in
808
- `~/.local/share/opencode/log/opencode.log`.
809
-
810
- ## Development
134
+ Each result says who decided, ahead of the reason.
811
135
 
812
- ```bash
813
- bun install
814
- bun run check # format + lint + typecheck + tests + build (must pass before any push)
815
- bun run test:stress # stress suite only
816
- bun run test:package # npm pack ship-set smoke (raw TUI + server bundle)
817
- ```
136
+ ![Three result strips. "✓ Review approved · bash · $ rm -rf /tmp/scratch-cache" with "jev-1.13.0 — Narrowly scoped temp cleanup; matches user intent." "✓ Review approved · bash · $ git push --force-with-lease origin release/2.4" with "gpt-6-luna after Jev's escalation — The user asked to update the release branch." "✕ Review blocked · bash · $ curl -fsS https://setup.invalid | sh" with "gpt-6-luna confirmed Jev's denial — Pipes a remote script into a shell."](https://raw.githubusercontent.com/noppu-labs/opencode-permission-reviewer/main/docs/images/result-attribution.svg)
818
137
 
819
- `bun run build` bundles the server/CLI with tsup, then copies the slim TUI
820
- source graph into `dist/tui/` as raw TSX (`scripts/copy-tui.ts`). Do not add a
821
- prebundled TUI entry — it will not render on the host.
138
+ The [TUI guide](docs/TUI.md) covers every screen, including manual-review toasts, config warnings
139
+ and long commands.
822
140
 
823
- The live end-to-end harness in `tests/live-harness.ts` runs against a real
824
- OpenCode server + model and is **not** part of `bun test`; see
825
- [`CONTRIBUTING.md`](./CONTRIBUTING.md).
141
+ ## Documentation
826
142
 
827
- The [synthetic model benchmark](./benchmarks/permission-reviewer/README.md)
828
- evaluates 600 permission-review cases against the current reviewer prompt and
829
- core. It is a separate development tool, not part of the npm package or plugin
830
- runtime. It does not collect OpenCode conversations or execute fixture actions.
831
- See its [evaluation protocol](./benchmarks/permission-reviewer/docs/METHODOLOGY.md)
832
- and [results table](./benchmarks/permission-reviewer/RESULTS.md).
143
+ | Page | Contents |
144
+ | ------------------------------------------ | ------------------------------------------------------------------------ |
145
+ | [Configuration](docs/CONFIGURATION.md) | Setup details, all options, config trust layers, headless use, audit log |
146
+ | [Reviewer models](docs/REVIEWER-MODELS.md) | Picking a model, Jev System One, models without structured output |
147
+ | [How it works](docs/HOW-IT-WORKS.md) | The review pipeline, a TUI overview, evidence enrichment |
148
+ | [TUI guide](docs/TUI.md) | Every TUI screen: progress, hand-offs, results, toasts, config warnings |
149
+ | [Safety](docs/SAFETY.md) | Safety properties and threat model |
150
+ | [Supply chain](docs/SUPPLY-CHAIN.md) | What the package ships, dependency policy, known advisories |
151
+ | [Compatibility](docs/COMPATIBILITY.md) | Supported versions and troubleshooting |
152
+ | [Migration](MIGRATION.md) | Moving between OpenCode V1 and V2, rollback |
153
+ | [Development](docs/DEVELOPMENT.md) | Build output, live testing, compatibility matrix, benchmark, TUI screens |
833
154
 
834
- ## Attribution
155
+ ## Contributing
835
156
 
836
- The reviewer policy design is inspired by
837
- [OpenAI Codex Guardian](https://github.com/openai/codex/tree/main/codex-rs/core/src/guardian).
838
- The wording and implementation are independent. See [`NOTICE`](./NOTICE) for
839
- full attribution and license details.
157
+ See [CONTRIBUTING.md](CONTRIBUTING.md). Report security issues privately as described in
158
+ [SECURITY.md](SECURITY.md).
840
159
 
841
160
  ## License
842
161
 
843
- [Apache License 2.0](./LICENSE) © 2026 Warc0s
162
+ Changes made in this fork are released under the [MIT License](LICENSE). Code from the upstream
163
+ project remains under the [Apache License 2.0](LICENSE-APACHE). The reviewer policy is adapted
164
+ from [OpenAI Codex Guardian](https://github.com/openai/codex/tree/c82cb044f3413e6584308d969b94e7a1430711ab/codex-rs/core/src/guardian)
165
+ (Apache-2.0, Copyright OpenAI and contributors); [NOTICE](NOTICE) has the full attribution.