Skip to content

Approval rules, part 1: gate, digest, and action plumbing (off by default) - #54

Merged
BunsDev merged 1 commit into
mainfrom
approval-rules
Oct 1, 2026
Merged

BunsDev merged 1 commit into
mainfrom
approval-rules

Conversation

@BunsDev

@BunsDev BunsDev commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Part 1 of the Jev-gated approval rules spec (2026-10-01-modex-jev-approval-rules-spec.md). This PR adds the plumbing, the gate, the digest, and unit tests. The gate is off by default and there is no UI, so nothing changes for users.

What's in it

  • ApprovalAction on ApprovalRequest (backends/types.ts), filled in by every backend:
    • Claude can_use_tool → { tool, title, cwd, input }
    • Codex commandExecution → { tool: "command", title: cmd, cwd, input: { command } }; fileChange → { tool: "fileChange", input: { paths, grantRoot? } }, with escalation: true when grantRoot is set. The paths come from the item's item/started; the patch body is never put on the action. permissions → { tool: "permissions", escalation: true }
    • Mock: the action is recovered from the question shapes @modex/core asks in (mockAction)
  • Settings: approval_rules: ApprovalRule[] (default []) and approval_gate (default { enabled: false, threshold: 0.8, timeout_ms: 3000 }), with normalisation in store.ts. Malformed rules are dropped and out-of-range gate values fall back to the defaults. Approval items gain an optional decidedBy receipt.
  • engine/approvals/digest.ts: the state Jev sees is built from an allow-list: tool, title, command (scrubbed, clipped to 500 characters), paths, project name and branch, and mode. old_string, new_string, content, patch, diff, edits[*], and any field not on the list are always dropped. The secret scrubber handles --token=…-style flags, Authorization: and similar headers, sk-, ghp_, github_pat_, xox*-, AKIA and JWT-shaped strings, URL credentials, and KEY=value env prefixes.
  • engine/approvals/gate.ts: the decision procedure from the spec:
    • A deterministic <tool>: <glob> pass, then one Jev request with one noul per rule plus destructive, capped at 12 rules (project-scoped first, then newest).
    • Precedence is never > ask > allow.
    • Safety downgrades: an allow on anything with destructive ≥ 0.5, or on an escalation, becomes ask.
    • If Jev errors, times out, or returns a malformed answer, only the deterministic result counts and the receipt says jev-unavailable. Otherwise the result is ask.
    • An abort answers "no".
  • Runner wiring (runner.ts sink approval):
    • The gate is consulted only when it is enabled, the request carries an action, and an enabled rule applies to the project. In every other case it runs the existing code path, synchronously as before.
    • allow answers "yes" (never "always") and adds an already-answered card with decidedBy. The thread never goes to waiting.
    • never answers "no" with a receipt.
    • ask shows today's card, with decidedBy attached when a rule or a downgrade caused it.
  • Router: Router.jev() exposes the router's already-resolved transport and model. It returns null when Jev is off for the session, and an auth or billing rejection seen through it turns Jev off just as routing does. No second key path.

Deviations from the spec (small; please check)

  1. Exact-match allows also get the destructive check when Jev is live. The spec runs the Jev pass only when there are rules without match. Under that wording, an exact-match allow such as Bash: * would never get the destructive downgrade, even though the spec says that downgrade "cannot be overridden by any rule". So the gate also asks Jev when the deterministic result would be allow. Without a transport, deterministic allows still stand, as the spec says.
  2. Command globs may omit the $ . Claude's Bash title is $ npm test. To make the spec's own example (Bash: npm test*) match, the glob is tried against the title both with and without a leading $ .
  3. downgraded: "jev-unavailable" is set whenever Jev was consulted and failed. When a deterministic allow or never still stands, that is how the receipt "notes Jev unavailable".
  4. Deferred to PR 2: extending the backend's deny message with (rule: …). That needs the sink to return a reason alongside the answer, and it is only visible once rules are on.

Deferred to PR 2

  • Settings → Approval rules UI, the "Try it" box, IPC (approvals:rules:get/set, approvals:try), receipt rows on the card, and e2e (e2e/approvals.spec.ts).
  • Turning the gate on by default (approval_gate.enabled: true).
  • Docs: AGENTS.md's "one network call outside the CLIs" sentence becomes "the optional Jev judge (Auto routing and approval rules)". Also the new docs/approval-rules.md, a pointer in docs/auto-routing.md, a README bullet, and docs/status.md. None of these change here because nothing user-visible ships until the gate turns on.

Tests

npm run build && npm test in the worktree:

@modex/core:    ℹ tests 15   ℹ pass 15   ℹ fail 0
@modex/desktop: ℹ tests 145  ℹ pass 145  ℹ fail 0

npm run typecheck is clean. I did not run e2e locally because there is no UI change; CI runs it.

  • approval-gate.test.ts (fake JevTransport):
    • precedence; the 0.79 vs 0.8 threshold edge; nothing applies → ask
    • destructive downgrade, including on an exact-match allow; escalation downgrade
    • match with a null transport
    • throw, timeout, malformed answer, and bad_response
    • the 12-rule cap and its ordering; project scoping
    • the digest is what Jev sees; abort → "no"
  • approval-digest.test.ts:
    • Claude Edit, Write, and MultiEdit carry no strings
    • Codex fileChange carries no patch
    • only allow-listed keys survive
    • clipping; scrubber cases
  • runner.test.ts:
    • a match allow answers "yes", lands an answered card with decidedBy, and the statuses are only running → idle
    • a never rule refuses a mock write
    • an ask rule keeps today's card with the rule attached
    • with the gate off, or with no applicable rule, the card is today's and carries no decidedBy
    • Jev through the Router's injected transport
    • stopping while Jev is pending answers "no"
  • claude-backend.test.ts / codex-backend.test.ts: action is filled in for each request kind. A rule's "yes" maps to allow without updatedPermissions (Claude) and to accept, not acceptForSession (Codex).
  • store.test.ts: defaults and normalisation.

Open questions for Val (answer before PR 2 flips the default)

  1. Default scope for new rules: all projects, or the current project?
  2. Without Jev live, should allow rules that have no match show as inactive in Settings, or be hidden? The spec currently shows them, marked inactive.
  3. Release slot: ship with v0.0.5 (the notarized build), or after it? This is not on docs/status.md Next yet.

Copilot AI balanced review requested due to automatic review settings October 1, 2026 16:19

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Transport setup can exceed the configured gate timeout, and Codex path tracking lacks lifecycle cleanup.

Review effort: Balanced
Findings: 2 Medium severity · 2 Low severity

Open (4)
What changed in this PR

Adds opt-in approval-rule infrastructure, structured backend actions, privacy-preserving Jev digests, and automated gate decisions.

Changes:

  • Adds approval-rule settings, receipts, normalization, and gate logic.
  • Supplies structured approval actions from Claude, Codex, and mock backends.
  • Adds unit coverage for decisions, redaction, persistence, and runner behavior.
File Description
apps/​desktop/​test/​store.test.ts Tests approval settings migration.
apps/​desktop/​test/​runner.test.ts Tests runner gate integration.
apps/​desktop/​test/​fakeproc.ts Captures structured approval requests.
apps/​desktop/​test/​codex-backend.test.ts Tests Codex approval actions.
apps/​desktop/​test/​claude-backend.test.ts Tests Claude approval actions.
apps/​desktop/​test/​approval-gate.test.ts Covers gate decisions and fallbacks.
apps/​desktop/​test/​approval-digest.test.ts Covers digest filtering and redaction.
apps/​desktop/​src/​shared/​types.ts Defines rules, gate configuration, and receipts.
apps/​desktop/​src/​main/​engine/​store.ts Normalizes and persists approval settings.
apps/​desktop/​src/​main/​engine/​runner.ts Integrates gate decisions into approvals.
apps/​desktop/​src/​main/​engine/​routing/​router.ts Exposes the resolved Jev transport.
apps/​desktop/​src/​main/​engine/​backends/​types.ts Defines structured approval actions.
apps/​desktop/​src/​main/​engine/​backends/​mock.ts Recovers actions from mock prompts.
apps/​desktop/​src/​main/​engine/​backends/​codex.ts Builds Codex approval actions.
apps/​desktop/​src/​main/​engine/​backends/​claude.ts Builds Claude approval actions.
apps/​desktop/​src/​main/​engine/​approvals/​gate.ts Implements rule evaluation and safeguards.
apps/​desktop/​src/​main/​engine/​approvals/​digest.ts Builds scrubbed Jev state.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +21 to +22
/** File paths of in-flight file changes, keyed `threadId:itemId`, so an approval can name them without the patch. */
private readonly changePaths = new Map<string, string[]>();
): Promise<{ ask: true; decidedBy?: ApprovalReceipt } | { ask: false; answer: "yes" | "no"; decidedBy?: ApprovalReceipt }> {
if (!c.active() || c.signal?.aborted) return { ask: false, answer: "no" };
try {
const jev = await this.router.jev().catch(() => ({ transport: null, model: "" }));
/**
* The approval gate: answers an approval from the user's plain-language rules before it reaches a
* human, or leaves it to the human. It never widens permissions (an allow is a one-off "yes") and
* fails closed: no rule, no key, an error, a timeout, or a malformed answer all mean "ask".

/**
* Runs the approval gate for one request. Resolves to a rule's answer ("yes" or "no", never
* "always"), or `ask` when a human must decide. Any failure is an ask; a stopped turn is a "no".
…ault)

Backends now attach a structured `action` to every approval request
(Claude can_use_tool; Codex command, fileChange, and permissions, with
grantRoot and permissions marked as escalations; the mock engine). A new
approvals/ module decides approvals from plain-language rules:
deterministic `<tool>: <glob>` matches first, then one Jev request (one
noul per rule plus `destructive`, capped at 12 rules) through the Router's
own transport. Precedence is never > ask > allow; destructive or
escalating allows become asks; any Jev failure falls back to the exact
matches, and everything else asks. Jev sees an allow-listed digest with
scrubbed command text and file paths, never file contents.

The runner consults the gate only when it is enabled and a rule applies to
the project. A rule-answered approval lands already answered with a
`decidedBy` receipt and never sets the thread to waiting; an allow is a
one-off "yes", never "always". Settings gain `approval_rules` (default [])
and `approval_gate` (default off). With the gate off, approvals follow the
existing path unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@BunsDev
BunsDev merged commit 67e4a1d into main Oct 1, 2026
2 checks passed
@BunsDev
BunsDev deleted the approval-rules branch October 1, 2026 23:24
BunsDev added a commit that referenced this pull request Oct 1, 2026
* docs: bring status.md up to date with what is in flight

In flight said "Nothing", but approval rules part 1 (#54) merged with
part 2 pending, four contributor PRs are open, and three worktrees hold
unlanded work. Record those, the #53 release-script change, the EPIPE
failure on main CI for c9dcc7d, and #39 as an icon candidate for v0.0.5.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: record the second terminal-cleanup CI failure

#63's push run failed "cleanup timeout retains ownership and a later
close can retry" with kill ESRCH from its SIGCONT cleanup; the
pull_request run of the same commit passed. Widen the rough edge to
cover both intermittent failures in terminal-cleanup.test.ts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants