Skip to content

Ordered permissions: one allow/deny/ask rule list, an asker on every surface, a policies file - #611

Merged
FMXExpress merged 4 commits into
mainfrom
claude/opencode2-d-permissions
Oct 23, 2026
Merged

FMXExpress merged 4 commits into
mainfrom
claude/opencode2-d-permissions

Conversation

@FMXExpress

@FMXExpress FMXExpress commented Oct 17, 2026 •

Copy link
Copy Markdown
Owner

PR D of docs/opencode2-plan.md. Targets main — #609 and #619 (background jobs, which replaced #610) are both merged, and main is merged in, so this diff is only the permissions work.

What

PasClaw had four unrelated gates — plan-mode refusal of mutating tools, the sandbox's shell denylist and path rules, the family switches, the component's BeforeToolCall hook — and none of them let an operator say the ordinary thing: ask me before shell_exec, but git status and git diff are fine, and git push is never fine. This adds one ordered rule list that does, in the shape OpenCode 2.0 settled on.

"permissions": [
  {"tool": "shell_exec", "effect": "ask"},
  {"tool": "shell_exec", "resource": "git status*", "effect": "allow"},
  {"tool": "shell_exec", "resource": "git push*",   "effect": "deny"},
  {"tool": "github__*",  "effect": "ask"}
]
  • tool is a glob over the name, resource an optional glob over the call's primary resource. Last match wins; no match is no opinion, so an empty list changes nothing.
  • deny refuses with a result the model can read. ask goes to the surface's asker — TUI footer, CLI prompt, a permission_request desktop event answered by POST /v1/permissions/<id>, or the component's OnAsk — which can allow once, allow for the session, or deny. With no asker the answer is deny: an ask rule never quietly becomes allow.
  • allow is only an opinion; the denylist and the workspace boundary still run inside the tool.
  • <home>/policies.json holds a second list of the same shape, evaluated first, that PUT /v1/config cannot write — the team case is a gateway that owns the file.
  • pasclaw permissions list / test <tool> [resource] show the lists in evaluation order and what the gate would decide.

Review fixes

P1 — a policy file that could not be read left no policy denies at all. ReadPoliciesLocked cleared the rule list up front and then returned early on every failure (missing, unreadable, truncated, not JSON, no permissions array), so a policies.json being rewritten non-atomically left the process with nothing enforced for the length of that window. Worse, RefreshPolicies had already consumed the mtime, so a recovery write landing in the same filesystem timestamp looked identical to the bad one and the empty state became permanent.

The rules are now replaced only after a successful read, and only a file that is gone clears them (an explicit [] clears them too — that is a file saying so). An unusable read keeps what is in force, counts itself, logs it, and permissions list warns that what is in force is not what is on disk. The change stamp is mtime and size, because size is what lets the recovery be seen inside one timestamp. Telling [] apart from a truncated array needs the array to have parsed, so that is checked before the possibly-empty parse result is trusted.

P1 — resource-scoped rules did not reach the search tools. ResourceOf mapped a hard-coded list of file-tool names, which went stale the moment the Glob/Grep pair landed: grep_files and find_files both take a path, neither was listed, so a policy denying /etc* for every tool did not match grep_files({"path":"/etc"}). The named special cases stay (command for the shell tools, code for execute_code, url for the fetch tools) and everything else now reads its path, else url, else command. Shorter than the list it replaces, and it cannot go stale.

apply_patch is the one real gap left and no field closes it: its paths are inside the patch body, several of them, and a glob over that text would match by accident as often as on purpose. Scope it by tool; the sandbox's path rules still bound where it writes.

P1 ×2 — two parallel asks shared one prompt, on both console surfaces. Tool calls dispatch in parallel, so one batch can hold two ask-gated calls. The TUI kept a single pending slot and one manual-reset event: the second request overwrote the first, and one keypress woke both waiters with the same answer — approving a call the operator never saw. The CLI had two threads printing to one terminal and calling ReadLn on one stdin.

Both now hold BeginInteractiveAsk / EndInteractiveAsk for the whole of one ask, so requests are presented in turn and an answer always belongs to the request that was shown. The gateway deliberately does not take the turn: its requests carry ids, each has its own event, and the web UI answers them individually — that surface was already correct.

Not in the review: TTUI.Destroy freed FAskLock and FAskEvent while a loop thread could still be parked in AskPermission (the bounded wait hands it to FreeOnTerminate after 250 ms, so Destroy cannot know it has left). They are left alone now, like FToolActivityLock, with the reasoning recorded beside it.

Tests

permissions_tests: GlobMatch; ResourceOf; EvaluateRules last-match-wins; parse/ToJSON round-trip; Decide precedence and the policy-file reload; session-allow memory; and the dispatch gate end to end (deny, ask with no asker, allow-once, allow-session, no rule, mode refusal first).

Added with the review fixes, each negative-verified by reverting the fix:

  • a truncated, empty or wrong-shaped policy file keeps the rules in force; [] and deleting the file clear them; the recovery write is adopted with no sleep between writes, which only works because the stamp includes the size.
  • ResourceOf for grep_files, find_files, the file family and its fs_* aliases, kb_get, an unknown MCP-shaped name, the url and command fall-through — plus the review's own scenario end to end.
  • two threads taking the ask gate five times each never overlap; reverting the gate to a no-op reports nine overlaps.
  • both console askers are checked to hold the gate (comments stripped first), since neither can be driven from a test.

On this head, with main merged in: build, lint-pascal-shape, test-permissions, test-subagent-bg and test-shell-timeout green; the merge was conflict-free.

Docs

docs/security.md, docs/configuration.md (permissions, permissions_ask_timeout_sec), docs/commands.md, docs/gateway.md.


🤖 Generated with Claude Code

https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U

…surface, a policies file

PR D of docs/opencode2-plan.md. PasClaw had four unrelated gates --
plan mode's refusal of mutating tools, the sandbox denylist and path
rules, the family switches, the component's BeforeToolCall hook -- and
none of them let an operator say the ordinary thing: "ask me before
shell_exec, but git status and git diff are fine, and git push is
never fine". This adds that, in the shape OpenCode 2.0 settled on.

config.json "permissions" is an ordered list of {tool, resource?,
effect}. tool is a glob over the tool name; resource is a glob over the
call's primary resource (the command for shell tools, the path for file
tools, the url for fetch tools, the script for execute_code). The last
matching rule wins; no match means no opinion, so an empty list changes
nothing. PermissionGate runs in DispatchOneToolCall after the mode
gates and before preflight. deny lands in ResultText like the mode
refusals, naming the rule and telling the model not to retry. ask
blocks the dispatching thread on the loop config's OnAsk until a human
answers: allow once, allow for this session (remembered under the
session key for that tool + resource), or deny. With no asker wired --
a cron run, a piped agent, a gateway with no web UI connected -- an ask
rule denies. It never quietly becomes allow.

The askers: the Delphi TUI parks the request and shows it in the
footer (Y once, S session, anything else deny) while the loop thread
waits on an event; the FPC line TUI and the CLI REPL read one line on
stdin; the gateway publishes a permission_request desktop event and
waits for POST /v1/permissions/<id> (GET /v1/permissions lists what is
pending; no subscriber on the event feed means deny at once); the
TPasClawAgent component fires OnAsk on the dispatching thread.
permissions_ask_timeout_sec (300) bounds every wait.

<home>/policies.json holds a second list of the same shape. It is
evaluated first: a policy deny is final, a policy ask outranks a config
allow. PUT /v1/config writes config.json only, so a web UI session can
edit its own rules but cannot loosen the policies. The file is re-read
when its mtime moves, so an operator edit lands without a restart.

The rules live as a locked process-global in PasClaw.Permissions
(dispatch happens on loop threads and parallel workers) and are
installed by ApplyConfigGlobals, which every LoadConfig runs.
`pasclaw permissions list` prints both lists in evaluation order;
`pasclaw permissions test <tool> [resource]` prints the decision and
the rule that made it.

Tested in permissions_tests: glob semantics, ResourceOf per tool
family, last-match-wins with tool-only and resource rules, parse and
JSON round-trip with bad effects skipped, Decide precedence across the
two lists, the policy file appearing, changing and disappearing by
mtime, session allows per key and resource, and the dispatch gate
through MakeLoopDispatcher: deny never runs the handler, ask with no
asker refuses, an asker's deny / allow once / allow session behave,
and the plan-mode refusal still comes first.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-17T07:58:18.938584Z 274a075 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 274a075204

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/pkg/config/PasClaw.Permissions.pas Outdated
Obj: TJsonObject;
Arr: TJsonArray;
begin
SetLength(GPolicies, 0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep the last valid policy set on reload errors

When an existing policies.json is temporarily unreadable or contains partial/invalid JSON during a non-atomic update, this clears GPolicies before validating the replacement. Tool calls during that window—and potentially afterward when the final write has the same filesystem mtime—run without the previously enforced policy denies. Parse into a temporary array and replace the active policies only after a successful read and parse; deletion can still explicitly clear them.

Useful? React with 👍 / 👎.

Comment thread src/pkg/config/PasClaw.Permissions.pas Outdated
Comment on lines +254 to +256
else if (Copy(N, 1, 3) = 'fs_') or (N = 'read_file') or (N = 'write_file') or
(N = 'append_file') or (N = 'edit_file') or (N = 'list_dir') then
Result := ArgStr(ArgsJSON, 'path')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Extract resources from canonical search tools

Resource-scoped policies are bypassed for the canonical grep_files and find_files tools because both accept a path but fall through here to an empty resource. For example, a policy denying tool="*" on /etc* does not match grep_files({"path":"/etc",...}), so the search proceeds whenever the underlying sandbox permits it. Include all path-bearing canonical tools in this mapping rather than only their fs_* aliases and the listed file operations.

Useful? React with 👍 / 👎.

Comment on lines +601 to +605
FAskEvent.ResetEvent;
FAskAnswer := aaDeny;
FAskPending := True;
FAskLine := ToolName;
if Res <> '' then FAskLine := FAskLine + ' ' + Res;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Queue concurrent TUI permission requests separately

When a model emits two ask-gated read-only calls in the same parallel batch, both worker threads share this single manual-reset event and overwrite the same pending line and answer. One keypress sets the event, wakes both workers, and both return the same approval even though the footer displayed only the last request, allowing an unseen tool call. Serialize permission requests or give each request its own state and event.

Useful? React with 👍 / 👎.

Comment thread src/cmd/PasClaw.Cmd.Agent.pas Outdated
Comment on lines +288 to +290
Print(' allow [y]once / [s]ession / [n]o > ');
if EOF then Exit;
ReadLn(Line);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Serialize CLI permission prompts across worker calls

The CLI enables parallel dispatch, so multiple ask-gated read-only calls can invoke this method concurrently and block separate worker threads on the same stdin stream. Their prompts interleave, and a response intended for the request most recently shown can be consumed by the other worker, approving the wrong tool/resource. Route these requests through one serialized prompt queue before reading stdin.

Useful? React with 👍 / 👎.

Four conflicts, all from both sides touching the same lines:

  Makefile / docs/configuration.md -- this branch's new rows and target
  sit where #608's tree-kill rewording landed. Kept both.

  PasClaw.Config.pas -- ApplyConfigGlobals: main renamed the shell
  timeout setter to SetShellToolTimeoutMs, this branch added the
  permission-rule wiring right beside it. Kept both.

  PasClaw.TUI.pas -- TTUI.Destroy. #610 moved FBgFlashLock.Free to the
  end (after the thread hand-off) and this branch had added the ask
  state's Free beside it at the top. Resolved by not freeing the ask
  lock or event at all: a worker parked in AskPermission leaves it
  within a poll slice of FQuit, but the bounded wait hands the thread to
  FreeOnTerminate after the same 250 ms, so Destroy cannot know it has
  left -- the same reasoning the file already records for
  FToolActivityLock.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
…reach every tool, one prompt at a time

Four review findings, all P1, all confirmed.

**A policy file that could not be read left no policy denies at all.**
ReadPoliciesLocked cleared the rule list up front and then returned
early on every failure -- missing, unreadable, truncated, not JSON, no
"permissions" array -- so a policies.json being rewritten
non-atomically left the process with nothing enforced for the length of
that window. Worse, RefreshPolicies had already consumed the mtime, so
a recovery write landing in the same filesystem timestamp looked
identical to the bad one and the empty state became permanent. The file
a team gateway owns is exactly the file that gets rewritten under a
running agent.

Now the rules are replaced only after a successful read, and only a
file that is GONE clears them (an empty array clears them too -- that
is a file saying so). An unusable read keeps what is in force, counts
itself, and says so in the log; `permissions list` warns that what is
in force is not what is on disk. The change stamp is mtime AND size,
because size is what lets the recovery be seen inside one timestamp.
Telling `[]` apart from a truncated array needs the array to have
parsed, so that is checked before the (possibly empty) parse result is
trusted.

**Resource-scoped rules did not reach the search tools.** ResourceOf
mapped a hard-coded list of file-tool names, which went stale the moment
the Glob/Grep pair landed: grep_files and find_files both take a path,
neither was listed, so a policy denying `/etc*` for every tool did not
match grep_files({"path":"/etc"}) and the search went ahead on whatever
the sandbox allowed. A list of names has to be revisited by whoever adds
a tool -- including an MCP server, whose tools nobody here will ever
name -- and nothing makes them. The named special cases stay (command
for the shell tools, code for execute_code, url for the fetch tools) and
everything else now reads its `path`, else `url`, else `command`. That
is shorter than the list it replaces and cannot go stale.

apply_patch is the one real gap left and no field closes it: its paths
are inside the patch body, several of them, and a glob over that text
would match by accident as often as on purpose. Scope it by tool; the
sandbox's path rules still bound where it writes. Said so in the code
and in the docs.

**Two parallel asks shared one prompt, on both console surfaces.** Tool
calls dispatch in parallel, so one batch can hold two ask-gated calls.
The TUI kept a single pending slot and one manual-reset event: the
second request overwrote the first, and one keypress woke both waiters
with the same answer -- approving a call the operator never saw. The CLI
had two threads printing to one terminal and calling ReadLn on one
stdin, so the line meant for the prompt on screen could be consumed by
the other thread.

Both now hold BeginInteractiveAsk/EndInteractiveAsk for the whole of one
ask, so requests are presented in turn and an answer always belongs to
the request that was shown. The gateway deliberately does not take the
turn: its requests carry ids, each has its own event, and the web UI can
answer several individually -- that surface was already correct.

**Not in the review:** TTUI.Destroy freed FAskLock and FAskEvent. A loop
thread parked in AskPermission leaves within a poll slice of FQuit, but
the bounded wait above hands the thread to FreeOnTerminate after the
same 250 ms, so Destroy cannot know it has left -- freeing the event it
may be waiting on is the use-after-free the hand-off is designed around.
They are left alone now, like FToolActivityLock, with the reasoning
recorded next to it.

Tested (test-permissions), each fix negative-verified by reverting it:

  - a truncated, empty or wrong-shaped policy file keeps the rules in
    force; `[]` and deleting the file clear them; the recovery write is
    adopted with no sleep between writes, which only works because the
    stamp includes the size. Reverting the clear-up-front fails on the
    truncated case; reverting the size half fails on the stamp.
  - ResourceOf for grep_files, find_files, the whole file family and its
    fs_* aliases, kb_get, an unknown MCP-shaped name, url and command
    fall-through, and nothing for a tool with none of them; plus the
    review's own scenario end to end (deny `/etc*` for `tool:"*"` now
    denies grep_files on /etc and still allows /home/me).
  - two threads taking the ask gate five times each never overlap;
    reverting the gate to a no-op reports nine overlaps.
  - both console askers are checked to hold the gate, since neither can
    be driven from a test (one paints a footer and answers from a key
    handler, the other blocks in ReadLn). The check strips comments
    first, so a comment that names the call cannot satisfy it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
@FMXExpress
FMXExpress changed the base branch from claude/opencode2-c-async-shell to main October 23, 2026 05:25
FMXExpress pushed a commit that referenced this pull request Oct 23, 2026
…lag, and refuse before touching the repo

This branch now targets main. It brings in the updated #611 branch,
which carries main -- #609 code mode and #619 background jobs, both
merged -- so the PR's diff against main is permissions plus worktrees
until #611 lands, then worktrees alone. Worktrees depend on #611: they
add resource mappings to PasClaw.Permissions, the file #611 creates.

Three conflicts:

  docs/configuration.md -- this branch's worktree rows sat where main
  reworded shell_timeout_sec. Kept both, and said that
  worktree.enabled:false takes the spawn argument away too.

  PasClaw.Permissions.pas, ResourceOf -- this branch added
  worktree_remove/worktree_create cases to the old name list that #611
  replaced with a generic path/url/command fall-through. worktree_remove
  takes a `path`, which the fall-through already reads; worktree_create
  is named by its `branch`, which no generic field covers, so it keeps a
  named case.

  PasClaw.Agent.SubagentBg.pas, the spawn_background registration --
  #619 put it inside `if Length(Specs) > 0` so the shell tools survive
  subagents being off; this branch added a `worktree` schema property.
  Kept #619's structure; the property is now conditional (below).

And the two review findings, both P2, both real:

**worktree.enabled:false only took away one door of three.** Callers
dropped the worktree_* tools, but spawn and spawn_background still
advertised a `worktree` argument and still created a branch and a
checkout when it was passed. WorktreeArgEnabled (a nil Cfg reads as the
documented default, on) now gates both handlers, which refuse the
argument with a message saying how to proceed, and both schemas, which
stop offering it.

**spawn_background created the worktree before checking the job cap.**
A spawn the cap was always going to refuse still made a branch and a
checkout on disk, then returned the capacity error. Checking first is
not enough by itself -- two spawns in one parallel batch would both pass
and both create -- so the slot is reserved under the lock (FReserved,
counted by SlotsInUse alongside running jobs, and shell_background's cap
check counts it too), the slow git work runs outside the lock, and the
reservation becomes the job or is handed back on failure.

spawn had the same shape with its cheap checks: an unknown agent or an
empty prompt made a worktree on its way to being refused. EnsureWorktree
now runs after every check that can reject the call.

Tested (test-worktree), each fix negative-verified by reverting it:

  - with worktree.enabled:false, neither spawn nor spawn_background
    offers the property, both refuse it, and no directory or branch
    appears; with it on, spawn offers it again. Reverting the gate fails
    on the schema assertion.
  - spawn with an unknown agent or no prompt, and spawn_background at a
    cap of 1 held by a running shell job, each leave no worktree
    directory and no branch. Reverting the reservation fails on the cap
    case. Reverting spawn's ordering fails too -- on the flag test first,
    since the reverted order also runs ahead of the flag check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
@FMXExpress
FMXExpress merged commit 91860f7 into main Oct 23, 2026
FMXExpress pushed a commit that referenced this pull request Oct 23, 2026
#611 (permissions) and #612 (worktrees) are both in main now, so this
PR's diff against main is attach mode alone.

One conflict, docs/configuration.md: this branch's cli.attach row sat
where main reworded shell_timeout_sec (the tree-kill wording). Kept
both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
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