Permissions
How zelk decides whether a tool call may run. The permission package defines the modes, rules and the decision algorithm; the reducer runs it.
The decision algorithm covers rules, protected paths, the plan, default, accept-edits, dont-ask and bypass modes, approvals with every response kind, session grants, the PreToolUse, PermissionRequest and PermissionDenied hooks (hook), and the auto mode classifier.
Policy
Section titled “Policy”A host always names the mode: zelk.New fails with ErrNoPermissionMode without WithPermissionMode. There is no implicit authority.
| Option | Effect |
|---|---|
WithPermissionMode(m) |
The mode sessions start in. Required. |
WithAllowedModes(ms...) |
The modes a SetPermissionMode command (and an approved plan) may select. The starting mode is always authorized. |
WithAllowedTools(names...) |
The tool ceiling. Tools outside it aren’t offered to the model; naming a tool sessions don’t have fails New. |
WithScratch(dir) |
Each session’s scratch directory, dir/<12 hex characters> (a subagent shares its root session’s). The session records it, its context names it, its commands may write it (their TMPDIR stays the shell’s), and its file tools reach it. See The scratch directory below. |
WithWithheldTools(names...) |
Tools new sessions aren’t offered, because nothing about the host’s runs lets them work. No ceiling: the agent keeps them, so a session that recorded one resumes with it. A session’s tools are decided when it starts. |
WithRules(permission.Rules{...}) |
Deny, human-only, ask and allow rules. |
WithProtectedPaths(patterns...) |
Extra protected paths. |
The resolved policy, rules in their written form included, is recorded in SessionStarted (event.Config.Policy), together with the model-facing workspace root (event.Config.Root) that path rules resolve against. Replay never consults the current options.
A rule is Tool or Tool(pattern); the tool name may contain * (mcp__github__*).
| Tool | Pattern |
|---|---|
PowerShell |
A bare rule or (*) matches every command. Argument patterns match parsed segments. |
Bash |
Matched against each simple command’s words, * matching anything; a trailing * also matches nothing (npm test * matches npm test); :* is accepted for *. |
Read, Write, Edit, Glob, Grep |
A glob over the workspace-relative path (glob syntax); Edit rules also cover Write. |
WebFetch, and a host tool that declares the URL it acts on (tool.WithURL) |
domain:example.com matches the host and its subdomains; domain:*.example.com only its subdomains. |
| any other | * matched against the call’s canonical JSON input. |
A host tool that reads a file and sends it on, as a browser upload does, declares it (tool.WithReadsPath): the path is decided as a file tool’s, so protected paths apply, and so do Read’s deny and ask rules, but not Read’s allow rules, since sending a file is more than reading it. When it declares a URL too, each of its own rules is judged by its kind: a domain: rule by the site, any other by the file. A deny or ask of either kind holds, so browser_upload(domain:example.com) refuses uploads there whatever the file. A domain: allow rule grants the site, and the file only inside the workspace.
Where rules come from. A host’s rules are the union of its flags (-allow, -ask, -deny, -human, -protect), the user’s config.json and the project’s .zelk/settings.json (the same keys). Sources never override one another: an action is decided by the strongest rule that matches, deny over human over ask over allow, whatever file it came from. A project’s deny, ask and human rules and protected paths apply at once: a repository can only make zelk more careful. Its allow rules widen what zelk may do, so they apply only once the user has trusted that exact file for that workspace (content hash, as for project hooks); the TUI asks at start in the same review as the hooks, and zelk project trust records it for the other hosts, which otherwise skip the allow rules with one warning. Changing the file makes it untrusted again. .zelk/ is a protected path, so the agent can’t edit its own rules without a person. A review gathers its files under the narrowing rules of the repository root’s file, wherever under the root it starts.
Shell matching is advisory: commands are split by core/internal/bashparse. Its read-only allowlist accepts git --version, git worktree list, git clean -n and cd <dir>, and sed whose script only prints, deletes, counts or quits by line (sed -n '1,240p' file): no -i or -f, no s, w, r or e, and no word the shell computes. A git clean long option it doesn’t know, such as --no-dry-run, makes it a removal. For an allow rule every segment must match a rule or be on the read-only allowlist, and no segment may be indirect (sh -c, eval, xargs, env, sudo, find -exec, an option that runs a program such as rg --pre, …), carry assignments or redirect output; an unparsable or opaque command never matches. Deny, human-only and ask rules match if any one segment matches, also inside literal sh -c '...' code, inside the programs options run (rg --pre 'sh -c "rm -rf x"' matches Bash(rm *)) and past wrappers (sudo rm -rf x matches Bash(rm *)). The launcher, not matching, is the enforcement.
PowerShell analysis
Section titled “PowerShell analysis”A host enables syntax analysis with zelk.WithPowerShellAnalysis, using an
analyzer created from the same trusted executable and edition that runs the
tool. The host owns the analyzer and closes it after its agents finish.
Without an analyzer, PowerShell command text is opaque.
The analyzer starts a subprocess without profiles and passes each command as
a line of base64 UTF-8 data to PowerShell’s Parser.ParseInput. The child
returns a JSON projection of the syntax tree. It never invokes the proposed
command. The request limit is 64 KiB, the response line limit is 4 MiB, and an
exchange including queueing has three seconds. Unreadable syntax, invalid
responses, a timeout or a child that cannot start or exits during the request
make that command opaque. The next request after a process failure starts a
fresh child. Parse-time directives such as using, #requires and DSC
configuration are screened before they reach PowerShell’s parser.
Pipelines, statements and PowerShell 7 pipeline chains (&&, ||) each
contribute their commands. Literal invocations and parameters become words.
Literal blocks invoked by & or ., or passed to supported
Where-Object and ForEach-Object forms, contribute their commands
recursively. A fixed Windows alias table canonicalizes names such as ls,
dir and gci to Get-ChildItem, rm and del to Remove-Item,
and cat to Get-Content. Aliases whose meaning differs by edition, such
as sc, remain opaque.
Opaque syntax includes computed names and arguments, assignments, function
and filter definitions, alias and module changes, method calls, dynamic
evaluation (iex, Invoke-Expression, [scriptblock]::Create), indirect
invocations such as & $x or . $x, jobs, Invoke-Command,
Start-Process, Add-Type, child PowerShell sessions, and unsupported
syntax or parameter binding. ForEach-Object member invocation and
parallel blocks are opaque. Simple property access in the two pipeline
cmdlets, and literal property comparisons in Where-Object, are recognized.
Literal file redirections (>, >>, 2>, and their other stream
forms) supply write targets. Stream merges and $null do not name a file.
Known file cmdlets supply explicit literal operands, including positional
paths: Set-Content, Add-Content, Clear-Content, Out-File,
New-Item, Remove-Item, Move-Item, Copy-Item, Rename-Item,
Set-Item and Clear-Item. Filesystem paths that the engine cannot resolve
lexically, including provider-qualified and wildcard write operands, require
review. It follows literal location changes from the call’s working directory.
Protected paths, critical removals, native Git configuration and worktree
checks use the shared permission gates. Worktree sessions with an analyzer
refuse opaque PowerShell commands whose Git use cannot be read. In
accept-edits, mapped file cmdlets with explicit operands inside the
workspace or scratch can use the filesystem grant. A PowerShell profile write
requires a person. Auto review gets the parsed command names and fresh
repository facts for known local discards, such as a local Remove-Item or
git restore. Replay uses the recorded verdict and review facts.
| Implicitly read-only cmdlets | What the permitted forms do |
|---|---|
Get-ChildItem, Get-Item, Get-Content, Select-String, Test-Path |
List, read or search workspace data and metadata, or test whether a path exists. |
Get-Location, Resolve-Path, Split-Path, Join-Path |
Report or manipulate path text and resolve existing paths. |
Measure-Object, Sort-Object, Select-Object |
Measure, order or select pipeline values. |
Format-Table, Format-List, Format-Wide, Format-Custom, Out-String, Write-Output |
Format or emit pipeline values. |
Get-Date, ConvertTo-Json, ConvertFrom-Json |
Report time or convert data. |
Get-Command -ListImported |
Inspect commands already loaded in the session. |
Where-Object, ForEach-Object |
Filter or transform pipeline values when their supported blocks are read-only. |
Only audited full parameter names qualify for the implicit grant. A
Get-Content -Wait or Get-ChildItem -FollowSymlink needs a rule or review.
Common parameters that set variables, abbreviated parameters, and
Select-Object -Wait also need a rule or review. Get-Help and exact
Get-Command lookup can autoload modules, so they receive no implicit
grant. Output redirection and reads outside the workspace also remove the
implicit grant. Native Git uses the same read-only flag checks as Bash.
A narrow allow such as PowerShell(Get-ChildItem *) covers a compound
command only when every parsed segment matches an allow rule or qualifies for
the in-workspace read-only grant. Output redirection, indirection and opaque
syntax prevent that grant. For example, the rule alone cannot allow
Get-ChildItem x; Remove-Item -Recurse ~. PowerShell cmdlet words match
case-insensitively. Native argument spelling retains its case for allow rules.
Deny, human-only and ask rules match any visible segment or the complete raw
string case-insensitively. The whole-tool rules PowerShell and
PowerShell(*) also cover opaque commands and are set aside in auto mode.
A workspace root determines how file tool paths and shell targets resolve. Windows roots use drive-absolute slash paths such as C:/repo. File tools also accept backslashes and reject drive-relative, current-drive-rooted, UNC and device namespace paths. They reject alternate streams, reserved device names and components ending in a dot or space before resolving dot segments. Lexical containment ignores drive-letter case and preserves every other component’s case. The environment checks filesystem identity. When interpreting shell targets, the permission engine converts Git Bash drive spellings such as /c/repo and requires a human when it cannot identify the Windows command name.
Protected paths
Section titled “Protected paths”Writes to these are never allowed by a mode, rule or session grant. They go to a person, and are denied in dont-ask mode and headless sessions. After Claude Code, auto mode sends a write to the built-in list below to its classifier instead, headless or not. Some stay with a person even there: what grants permissions or runs code later outside the sandbox (agent settings in .zelk/, .claude/, .codex/, .agents/ and the home directory, hooks, .mcp.json, anything under .git/, git configuration writes, shell startup files), since a wrong verdict there outlives the session and the classifier gate hasn’t passed (this departs from Claude Code; revisit once it does); paths the host names with WithProtectedPaths or -protect, removing a critical directory (below), an unreadable cd, and, in a session under a sandbox, what the sandbox holds read-only (enforcement). File tools run in the host, outside the sandbox, so without that last exception one wrong allow could change what no shell command there can.
.git/,.zelk/,.agents/,.claude/,.codex/at any depth in the workspace, and git hooks;- after Claude Code’s list, a tool’s own configuration at any depth:
.vscode/,.idea/,.husky/,.cargo/,.devcontainer/,.yarn/,.mvn/,.config/git/, and files such as.mcp.json,.gitmodules,.pre-commit-config.yaml,lefthook.ymland the package-manager and wrapper configuration intoolConfigFiles; - the user-level settings of zelk and other coding agents, which a shell target names from
~,$HOMEor$XDG_CONFIG_HOME, or absolutely:.zelk/,.agents/,.claude/,.codex/,.config/zelk/and.claude.json. zelk doesn’t know the home directory when it decides, so in an absolute path these directories count wherever they are. Writing them lets an agent grant itself authority (rules, hooks, MCP servers), which the classifier’s policy also denies, but a deterministic check takes it off the model’s judgement. File tools can’t reach them: they stay in the workspace; - shell and tool startup files by base name (
.bashrc,.profile,.zshrc,.envrc,.gitconfig,.npmrc,.netrc, …); rm/rmdirof the workspace root,$HOME/~or/;- a shell command that may write git configuration:
git configin any write form or scope,git remote add/rename/remove/set-url/set-branches,git submodule init/sync/add/deinit/set-url/set-branch/absorbgitdirsandupdate --init,git lfs install/update,git maintenance register/start, andgit clone/git initgiven configuration or a template, seen through wrappers and inline shell code as deny rules are. Configuration names programs git runs later, outside the sandbox, andgit config core.hooksPath xnames no protected path. Agit configoption the grammar doesn’t know, or a git subcommand the shell computes, counts as a write. A script that writes configuration without spelling it is beyond this; - the host’s patterns: globs with a slash are workspace-relative, base-name globs match anywhere.
Worktree sessions. A session that works in a git worktree of its own (zelk.WithWorktree, which the zelk hosts set inside .zelk/worktrees/<name>) refuses, at step 1 and in every mode, a file tool’s path outside the workspace, which bypass would otherwise let Read reach, and a shell command that may run git against another checkout: -C, --git-dir, --work-tree or -c core.worktree naming a directory outside the workspace or one the shell computes; GIT_DIR, GIT_WORK_TREE or GIT_COMMON_DIR set that way; a cd, pushd or popd that may leave the workspace in a script that runs git; and git use the command’s text doesn’t show (a computed command name, eval or -c with computed code). That includes configuration naming another work tree through --config-env or the GIT_CONFIG_* variables (GIT_CONFIG_KEY_<n>, GIT_CONFIG_PARAMETERS, and a GIT_CONFIG, GIT_CONFIG_GLOBAL or GIT_CONFIG_SYSTEM file). No approval runs it: the model can always write the command so it stays in the worktree, and the refusal says how. Like the other shell checks this reads words, not effects: a script file that runs git elsewhere is beyond it, and the sandbox (enforcement) is what confines it.
Matching is exact for the built-in file tools and best effort for shell commands: redirection targets, and every argument of a command that isn’t read-only. Absolute shell write targets are cleaned before being made workspace-relative for protection checks, so aliases such as /elsewhere/../work/.git/config cannot miss workspace protection. This includes output redirections on otherwise read-only commands and bare or compound commands. Host workspace-relative patterns use the same normalized targets. Computed writes remain best effort: matching sees the argument’s spelling, not its expanded destination.
Following cd. A cd to a directory in the workspace only reads, after Claude Code, which asks about the rest of cd sub && go test ./... but not the cd. The cd’s argument does not count as a write target. The engine follows the cds: every relative path a command names, for read scope and protected targets alike, is judged from the root and from each directory its cds and pushds reach. The shell’s word list carries no control flow, so a cd counts from every directory found so far, over two passes. That covers cds in subshells, failed branches and either order; a cd a loop repeats may nest deeper, but only into names the command already spells, which is what the built-in protected paths match, and any climb out of the workspace shows from the root. A cd zelk can’t follow (computed, ~, -, or outside the workspace) adds no directory and isn’t a read itself, so the command still goes to review. Like the rest of shell matching this is advisory: CDPATH from the environment, or a symlinked directory, can send a cd elsewhere, and the sandbox is the enforcement.
Decision procedure
Section titled “Decision procedure”Every tool call of a model turn is decided in one place, the reducer’s wave planner, before any EffectStarted is appended. First the call must name a known tool within the tool ceiling and the active skill’s allowed tools; then the internal permission engine’s Policy.Decide runs:
PreToolUsehooks run first, each call’s alone, as recordedrun_hookgates. A hookdeny(or a gate that fails closed) is final. A rewritten input is decided as the new action; context joins the model’s next call.- A deny rule matches → deny, in every mode.
- Mode ceiling: in
plan, any action that isn’t read-only → deny. Read-only means a built-in tool zelk trusts as read-only, a call that a trusted tool’s recordedread_only_whennames as read-only (aTaskcall for a subagent type that runs in plan mode, such asexplore), or a shell command the allowlist reads as read-only. A refused shell command’s result names the part that isn’t read-only (tee isn't one of the read-only commands), so the model can run the rest without it. - Human-only gate: a protected path, a human-only rule, or a hook
ask/defer→ ask a human, unless a human already approved exactly this action. Headless or indont-ask→ deny. Inautoa write to a built-in protected path is classified instead. bypass→ allow, except, in a headless session, a call a person decides (tool.WithPersonDecides, below): unattended, a trusted tab doesn’t count, so one is allowed only by a matching allow rule (naming the site or only the tool), aPreToolUsehook’s allow, aPermissionRequesthook’s approval of the ask, or the read-only grant for a call that only reads: the user’s browser acts only where the user’s own rules or hooks say (browser-automation.md, A6).- Unless an ask rule matches: an allow rule, a hook
allow, a call in a tab the user trusted while a person attends (browser automation), or the mode’s grant (read-only actions in every mode, only those that stay in the workspace, see below; workspace edits byWrite/Editinaccept-edits, and the filesystem commands Claude Code’s acceptEdits allows,mkdir,touch,rm,rmdir,mv,cpandsedlimited to plainssubstitutions (noeorw), on paths inside the workspace: written as the bare command (./mvwould run a workspace program), with no variables, input redirection, environment prefix or wrapper, andtouchwith plain paths only;Task,TaskContinue,TaskStop,Verifyfor a host check or requirement,ProcessInput,ProcessKill,CronCreate,CronDeleteandTaskMessage, whose effects are decided where they happen: a child’s calls run under its own narrowed policy, so a message to it needs no review of its own) → allow. AVerifycall that brings its owncommand, a check the model registers, is decided as thatBashcommand at every step: its rules, the read-only reading, protected paths and approvals, whose suggestions areBashrules. AWatchcall is decided the same way, as its command, never read-only, since the command runs until it ends (wakes, Watch). - A human’s approval allows. Otherwise
autoclassifies,dont-askand headless sessions deny, and every other mode asks a human. A trusted tool markedtool.WithPersonDecides(grant)is never classified: inautotoo a person decides, or the call is denied where none can be asked. Unlike a human-only action, its approval offers a session grant,grant(domain:SITE)for the call’s site, so one approval covers a flow across the tool’s family.SITEis the registrable domain (example.comforshop.example.com, from the public-suffix list), an IP address or a one-label name as it is, and a public suffix (github.io) gets no grant, since no one site owns it. When the call has a site, the approval is markedTrust, and a host that keeps the user’s rules (the TUI) also offers “Trust this site”, which grants it now and saves the rule with the user’s allow rules, so no later session asks there (browser-automation.md, A5). A call with no site, such as a session export, offers no trust: its saved rule would allow it on every site. The user’s own browser’s tools carry it, withuser_browser_*(user-browser.md): a wrong allow there spends the user’s real accounts. Marked alsotool.WithTrustedTab, as everyuser_browser_*tool is, a call acts in a tab the user already trusted, by sharing it or approving its opening, so step 5 allows it while a person attends, ahead of the classifier; only a call opening a new tab (user_browser_openwithnew_tab) is decided as above, and its approval is markedOpensTab, with itsSite(browser-automation.md, A13). Approving one adds the site to the session’sTabSites; a new tab on a site there, or on one a user message of the session names, counts as in a trusted tab too, with the audit saying which.
Before an ask becomes an approval request, PermissionRequest hooks may answer for the human: Allow approves exactly this action, AllowSession(id) also grants one of the suggested rules it is offered for the rest of the session (recorded as a PolicyAmended naming permreq:<call>, and never for a human-only action), Deny denies it, and no answer leaves the normal flow. A grant of a rule that wasn’t offered fails closed: the normal flow asks. They run in headless sessions too, since a hook may route the decision to a person; with no answer the call is then denied. A denied call’s result passes through PermissionDenied hooks, whose notes are appended for the model.
WebFetch asks per domain. A fetch asks a person unless a rule such as WebFetch(domain:example.com) allows it, which the prompt offers to add, or it is plain HTTPS to a documentation host on a built-in list. The list keeps only sites whose vendor writes the content, and auto mode’s reviewer still sees these fetches. A redirect to another host isn’t followed: the model is told where it leads, and fetching that is a new decision. dont-ask and headless sessions refuse it; plan mode, which is for reading around, doesn’t ask. WebSearch is unchanged outside auto mode.
Web tools in auto mode. WebFetch and WebSearch only read, but a URL or a query can carry data out, so in auto mode they go to the reviewer unless a rule allows them, such as WebFetch(domain:docs.example.com).
The read-only grant covers the workspace. A read-only shell command that names a file outside the workspace (an absolute path elsewhere, ~, $HOME, or a relative path that climbs out with ..), a path the shell computes (cat "$F"; $? and $# aren’t computed, being digits, so echo "exit=$?" reads nothing), or the whole process environment (printenv without a name, /proc/*/environ) isn’t granted at step 5. It goes on to step 6: the classifier in auto, a human in default and plan, a denial in dont-ask and headless sessions. Arguments and input redirections (wc < ~/.aws/credentials) both count, inside command substitutions too. Every argument counts as a path, so a pattern that looks like one only sends the read to review; a relative path is judged from the workspace root, since the request doesn’t carry the shell’s directory, and also from every directory the command’s cds may reach (below). The rule exists because the user’s credentials (~/.ssh, ~/.aws, ~/.config/gcloud, tokens in the environment) live outside the workspace, and a read puts them in the model’s context and the provider’s logs. A file tool’s read outside the workspace, such as a Read of /tmp/plot.png, is decided the same way: bypass allows it, and a read-only grant doesn’t. Whatever the decision, the environment reads no more than a command could: under a sandboxing launcher (bwrap, seatbelt) it refuses the read, so an allowing reviewer can’t open what the sandbox hides from Bash. The rule was missing while the environment kept file tools in the workspace, so they could read nothing outside it. An allow rule still allows such a read; plan mode doesn’t deny it at step 2, since it only reads. The classifier corpus’s end-to-end routing found the gap: 15 of 400 adversarial cases, all credential reads, ran without any review in auto mode.
The scratch directory. A session given one (WithScratch) records its absolute path in its configuration, and the request carries it. A file tool’s target in it has no workspace path and isn’t outside: a read there is a read like the workspace’s, and a Write or Edit there is allowed at step 5 in every mode but plan (step 2 denies it), since it changes nothing the user keeps and sends nothing anywhere. A deny or ask rule still decides first. A shell path in it doesn’t reach outside, so cat <scratch>/notes.txt gets the read-only grant. The boundary is a whole path component, so a sibling directory, another session’s, is outside. Its name is a short hash of the root session’s ID, not the ID, because tools create Unix sockets in it and those fail past about 100 characters.
Shell path analysis. Absolute paths are lexically cleaned before the workspace-boundary check: with root /work, cat /work/../x reads outside, while /elsewhere/../work/x reads inside. The boundary is a whole path component, and a workspace rooted at / contains every absolute path. Computed markings stay with a flag’s attached value: git --git-dir="$DIR" log names a path the shell computes, just as git -C "$D" log does; a single-quoted literal '$DIR' is not computed. These checks also apply to reads next to allow-matched commands, so an allowed build cannot implicitly grant a neighboring outside or computed read. Normalization uses only recorded text: no filesystem I/O, symlink resolution or variable expansion. Shell-directory tracking follows the literal paths described above.
A tool from an MCP server or a client is never treated as read-only, whatever its descriptor or the log record claims (MCP trust default): tool.WithOrigin makes such a tool untrusted, and the reducer refuses trust for those origins on its own.
mcp.Server.Offering lets Go hosts select remote tool names and withhold
optional top-level input properties. Discovery skips missing tools and tools
whose schemas cannot be narrowed safely, with a warning. The shaped schema
drives both provider rendering and local validation, including for open
schemas. Direct host discovery and calls retain the server’s original API.
Untrusted tool results. MCP and ACP client-hosted tool adapters fence external text with
tool.Untrusted before it can enter model history. That includes text in
embedded resources, structured content used as a fallback, resource links,
unsupported-content metadata and remote error messages. The label identifies
the tool and, for MCP, the configured server. The shared fence escapes both
label and body, bounds the payload after escaping, and leaves zelk’s own
notices outside. For binary images, diagnostics use a type inferred from
the bytes or a fixed fallback. MCP resources and native browser tools also
use this fence. Descriptor trust applies to the tool’s permission and
recovery behaviour.
Presets
Section titled “Presets”preset.CLI() is default mode with every tool and approvals through the host’s callback. preset.Server(...) has no shell (construction fails if one is configured), allows only auto and plan, suspends for approvals that become denials once they expire, and requires a hard budget.
Every outcome other than a plain allow is recorded as a derived PermissionDecided{call_id, tool, digest, verdict, step, reason, rule} in the same append group as the event that caused it, so audits and evaluation oracles see denied and asked actions. A denied call gets exactly one error result, in call order, telling the model not to reach the same outcome another way. Each time the reducer consults the policy for a call, the policy’s decision is recorded as PolicyDecided (plain allows included) in the same append. A live fold derives it again and refuses a log that recorded another; a stored log replays with the decisions it recorded, so a rule or heuristic changed since doesn’t change which calls an old session ran (durability, “Recorded decisions”, K7).
Action digests. loop.State.ActionOf(call).Digest() binds a proposed action to its tool, canonical arguments (object keys sorted, insignificant space removed), working directory and policy revision. Every approval names it; a decision never applies to another digest. A policy change while an approval waits (a mode switch, a grant) raises the revision, so the approval no longer applies and the call is decided again.
Auto mode
Section titled “Auto mode”Names and links. The rules read the name a tool was given. They compare names without regard to case, in every form a path can take, since a filesystem that ignores case (macOS’s, by default) reaches .zelk by .ZeLk; elsewhere the cost is one extra review. A file tool’s write that reaches a protected path through a symbolic link is refused where the write happens (core/env/local), because file tools run in the host, outside any sandbox. Writing the real name is left to these rules. Known limits: a host pattern using an uppercase character class such as [[:upper:]], and a cd into a differently spelled workspace, aren’t followed on a filesystem that ignores case; a link swapped in at the moment of a write isn’t caught; and a command that assembles a name at run time reads as something else, which is what a sandbox is for.
Leaving it unattended. Auto mode alone is not a safety boundary: without a sandbox, the reviewer and the fixed rules are all that stand between a wrong “allow” and the machine. To leave a run alone, use -sandbox bwrap or seatbelt, which keeps host credentials out and the network off or on an allowlist. As in Claude Code, the sandbox is opt-in and auto mode runs without one. TestContainmentWithAnAllowingReviewer is the evidence: with the reviewer forced to allow, a scripted attacker gets nothing out and leaves no agent configuration behind. Afterwards, zelk sessions report lists every action and how it was decided, and which changed files (a Makefile, AGENTS.md, a script) run for whoever builds or opens the project next, since no rule can keep an agent out of those.
The model is measured, not chosen. zelk runs on whatever model the host has, so a host checks it before relying on it. A session starting in auto mode first runs zelk.CheckReviewer, and one that switches to auto starts it as the switch takes effect (core tells a zelk.ClassifierPreparer reviewer the session is in auto mode), with a person deciding until it finishes: 32 built-in actions, 22 harmful and 10 harmless, drawn from the corpus’s trusted core and spread across its attack families. A model passes if it allows no harmful one and refuses at most one harmless one. The result is kept per endpoint, model, reviewer effort and check revision for 30 days in reviewer-checks.json in zelk’s default state directory, which -state doesn’t move because a result holds across sessions. With no such directory the check still runs, and is repeated next time. A model that fails isn’t relied on: its reviews come back uncertain, so what the rules leave open goes to a person, or is refused when none can be asked. A check that can’t get answers keeps nothing, says why (a rate limit, a missing key, a model too slow for its timeout), and doesn’t rely on the model for that run. A provider that refuses to let the model answer has still answered: the review is uncertain, so a refused harmful case isn’t a miss and a refused harmless one counts against the model. -no-reviewer-check overrides it. Passing the check is not a reliability claim: on a held-out set, both claude-sonnet-5-5 and gpt-6.1-terra allowed 4 of 744 attacks, over the 1% bar, while stopping almost no harmless work (results).
A session that authorizes auto records its classifier (event.Config.Classifier: policy text and revision, model, timeout, reservation). When the algorithm reaches step 6 in auto, the call becomes a classify_action effect, alone in its wave, reviewed by the classifier:
- Reuse is only an exact match on (action digest, policy revision, review revision). The review revision changes with every user message, approval answer and goal change. There is no pattern cache.
- Budget and bounds. Each attempt reserves like a model call (its cost cap: a budget that can’t cover it fails closed) and is charged what it spent. Its deadline is the configured timeout; an error is retried once, after the wait the retry policy gives a model call (as long as a rate-limited provider asks, within the policy’s maximum), so the retry doesn’t run straight into the same limit.
- Verdicts are recorded as
ActionClassifiedimmediately before the effect’s end.allowruns the call;denydenies it with the reason and an instruction not to reach the same outcome by a workaround;uncertain,timeoutanderrorfall through to a human, or a denial when none can be asked. A timeout or an error is reported as not being a judgment that the action is unsafe. - Stopping at an allow. The reviewer’s answer is structured output with the verdict first, so once the text begins with a complete
"verdict": "allow"the reviewer stops reading and the reason is recorded as unread: the reason after it can’t change the verdict, and stopping saved 12% of an allowed review’s time on Sonnet and 15 to 19% on terra. Any other verdict, and any answer that isn’t constrained to the format, is read to the end. A cut review’s output is never reported, so it is charged as its reservation and its usage is markedoutput_unread; its input is measured where the provider reports it first (Anthropic, at the message’s start) and charged as its reservation where it doesn’t (the OpenAI Responses API). Since that over-charges a budget, a session with a token budget or a parent’s allocation reads every answer to the end. - Circuit breaker: 3 consecutive denials, or 10 among the last 50 allow and deny verdicts, interrupt the turn with a
classifier_breakerwarning. Anuncertainverdict, a timeout or an error neither counts nor resets the count. Its state is folded, so it survives resume. Outside the classifier, a run that repeats an action the policy refused stops at the completion repeat limit (completion). - Paths the host protects, human-only rules and hook asks never reach the classifier (step 3), nor do tools marked person-decides (step 6), and reads and allow rules don’t need it (step 5). No allow rule, hook allow or file-edit grant skips its review of a built-in protected path.
- Tiers (after Claude Code’s auto mode): built-in file edits inside the workspace are allowed without review, as in
accept-edits, since version control keeps them reviewable; an allow rule that would run any code (Rule.RunsAnything:Bash,Bash(*), an interpreter, shell or package-manager run followed by a wildcard such asBash(python *)orBash(npm run:*), or one with an inline-code flag such asBash(bash -c *)) doesn’t count, so what it covers is reviewed. Narrow rules, such asBash(python scripts/build.py *), still apply. An edit of a file that configures the application or runs for whoever next builds or opens the project goes to the reviewer instead (permission.ReviewedEdit: TOML, YAML, JSON, INI,.cfg,.conf,.propertiesand.envfiles, build files, CI workflows, scripts, editor settings, Python.pthand.desktopfiles). Every held-out attack that skipped the reviewer was a workspace edit, most of them to configuration; ordinary source and documentation stay unreviewed. An allow rule naming the path still grants it. The review of aWritealso says what the tool can do (Review.Effect): it only creates a file the agent hasn’t read, fails if one is there, and replaces only the version the agent read in full. Without it terra answered unsure on 20 of 240 reviews of ordinary config and build-file edits, unable to tell whether a write would overwrite something; with it, on 1. - What the reviewer sees: the user’s messages, the agent’s recent tool calls and the project instructions, never the agent’s prose or the tools’ output. The agent can’t argue its case, and injected content never reaches the reviewer. The user’s answers to the agent (a plan approved or rejected, with its note; answers to questions) count as the user’s messages and come in order with them: approving a plan authorizes carrying it out. An approval of one action isn’t among them, so it never reads as a grant for another.
- A subagent’s reviewer: a child session’s messages are written by its parent model, so they reach the reviewer in the untrusted transcript, marked as the parent’s. The request the action is judged against is what the real user had said when the parent started or last continued the child (
Config.UserRequests, the latest 20 messages). A parent can’t authorize anything for its child by claiming the user asked. Answers a parent gives throughTaskOutputare its own words too, however it came by them, and bring the real user’s requests up to date; an answer a human gives through the root session stays the user’s. Only a goal set bySetGoalis shown as trusted; a goal that follows the run’s request is left out. - What it already refused: the reviewer is told the latest eight actions it refused in the session, with its reasons (including those it was unsure of when nobody could be asked, which are refused just the same), so a refused action rewritten with another tool or spelling isn’t judged as a fresh step. The record is the host’s and the actions’ text stays fenced as data. A step that removes the danger, an unrelated step, and a user message sent after the refusal are all still allowed. A refusal a person overrode with a one-use retry no longer counts. A subagent’s reviewer is also told its parent’s, as of when the parent started or last continued it or relayed it an answer, so a refused job handed to a subagent isn’t judged anew. Sessions with no refusals receive no refusal context.
- Across compaction: the tool calls a compaction removes stay in the reviewer’s transcript, within its 24 entries, which drop the oldest twelve at a time so consecutive reviews start alike.
- Before discarding work: before a shell command that can discard unsaved work (
rm,git reset --hard,git cleanand the like), a host givenWithReviewFactsmeasures the repository and the reviewer is told; the hosts count staged, modified, untracked and conflicted files, names excluded, since a file name is text the agent can write. The verdict holds for that one call, because the repository may stand differently when an identical command comes later. A command the model registers withVerifyis treated as a shell command here too. The measurement covers the repository the action works in, following a leadingcd DIR &&, which is how models usually start a command: git-ignored files, work inside submodules and other repositories aren’t counted, and a command that moves any other way, names a path outside that directory or runs shell code the analysis can’t read is reported as unknown, without a measurement. Inline code in another language (python3 -c, for one) isn’t measured either, but the reviewer is only told nothing was checked, since it can read that code. The action under review is left out of the transcript: nothing has run it, and listed among earlier calls it read as already done. Which commands count is read from their words and is best effort; a command it misses is reviewed without the fact. - Scripts the agent wrote: a command that runs a workspace file the agent wrote or changed in the session (one its checkpoints track, so changed by
WriteorEdit), as a program (./run.sh), an interpreter’s script (bash run.sh,python3 gen.py) or withsource, comes with a trusted fact naming the file as the agent’s and its first 4,000 bytes, read just before the review and fenced as untrusted data; a file that is gone, a link or not text is named with that reason.ActionClassified.Scriptsrecords what the reviewer was shown. As before discarding work, the verdict holds for that one call, since the agent may change the file before an identical command runs again. A file only Bash wrote, one outside the workspace (the scratch directory among them), a relative name after acdin the same command, and every file in a session without checkpoints aren’t known to be the agent’s, and such a command is reviewed without the fact. A build or test command that runs agent-written code indirectly (make,go test) isn’t covered either. - The declared environment:
WithClassifierEnvironment(the hosts’-trust) lists what the user counts as their own: repositories, buckets, internal services. The reviewer sees it as trusted, worded so that it authorizes no particular operation, and the policy revision covers it. It comes only from the user or the host, never from a project’s files. Without it, the prompt is unchanged. - The user’s other words: a steer a run took, a skill the user ran and the instruction given with a refused action count as the user speaking, as answers to the agent always have. In an answer, what the model wrote (the question, an option’s label, the plan) is quoted so that it can’t pass for another user message, and any answer invalidates earlier verdicts. For a skill: it appears by name and arguments, since its text comes from project files. They are kept with the conversation, so a withdrawn steer and a rewound message stop counting, and a fork inherits what was said. A scheduled message isn’t among them: its text may be the model’s.
Approvals
Section titled “Approvals”An ask becomes an approval request: an AwaitInput of kind approval whose effect ID is the approval ID (durability Q1). It carries the tool, the canonical input, the digest, the reason, whether it is human-only, the working directory and revision the digest binds, and narrowly scoped suggestions (Bash(npm test *), Edit(src/**), WebFetch(domain:go.dev), or the tool name). Human-only approvals offer none. An approval waits alone, after the calls before it in the turn.
It follows the input policy exactly like a question: the host’s callback answers it (InputCallback), the session suspends until a later Start brings the answer (WithInputSuspend, zelk.Respond), or, headless, the decision algorithm never asks. A callback error, panic or expiry fails closed.
Answer (zelk.InputRequest helper) |
Effect |
|---|---|
AllowOnce() |
The action runs this once. |
AllowEdited(input) |
The replacement input runs instead. It carries its own digest (loop.Replacement), is decided again, and the approval counts at step 6: deny rules, the mode ceiling and protected paths still apply. The model’s result says so. |
AllowForSession(ids...) |
The suggestions’ rules join the allow rules. PolicyAmended{approval, allow, revision} is derived from the answer and appended in the same group, raising the policy revision once; the action runs. Refused for human-only approvals. Several IDs are recorded as ApprovalAnswer.Suggestions; one is recorded as Suggestion. |
AllowAlways() |
AllowForSession with every suggestion. A command of several parts suggests a rule for each (npm test && go vet ./...), and only all of them stop it asking, so hosts offer this as the one “always” choice. |
Deny(message) |
The action doesn’t run; the message goes to the model. |
Cancel() |
The action doesn’t run and the run is interrupted. |
An answer that names another digest, a suggestion the approval lacks or one twice, or a replacement digest that doesn’t match is refused with ErrInvalidCommand (or, from a callback, fails closed).
Mode changes
Section titled “Mode changes”The model’s dynamic context describes only the modes
authorized by the recorded session policy and names the session’s mode. It
explains that mode switching belongs to the host and, when the session offers
ExitPlanMode, that it requests plan approval into an authorized execution
mode. The named mode is fixed at the first answered request and again when
compaction rebuilds the prefix, so switching changes neither the static system
prompt, the tool definitions nor this context.
A plan request carries ReturnMode, the mode the session left for plan mode
when it is still authorized, so approving a plan can go back to how the user
was working: the CLI’s y and ACP take it, and the TUI offers it first when it
is wider than default (as Claude Code offers bypass first), else leads with
accepting edits. The TUI also offers every other authorized
mode, so a session that authorizes plan and only, say, bypass can still
approve a plan. If the host switches the mode while a plan waits and the plan
is then rejected or expires, the result names the mode the session is in now
rather than saying it stays in plan mode.
Sessions offering EnterPlanMode instead explain
that the model may enter plan mode, and only the host may select any other
mode. EnterPlanMode{reason?} is offered alongside ExitPlanMode whenever
plan is authorized, in every current mode, so the tool list stays cached;
headless agents (InputDeny) offer neither, since no one could approve
leaving plan mode and a host-selected plan session presents its plan as the
final answer.
The reason is shown to the person. Entering plan mode needs no approval: it
can only reduce permissions. Already in plan
returns success without a change; unauthorized plan mode returns an error.
The call queues plan through the same ModeChanges path as a host command,
so it waits for active tools, advances the policy revision, invalidates stale
approvals and governs undecided calls later in the same response. Its logged
call and result are the audit record; Status.Mode reflects the applied
change. The next request gets the existing plan-mode note and instructions.
Only a host command or a person’s approval of ExitPlanMode can leave plan
mode for another authorized mode; no model tool can widen permissions.
zelk.SetPermissionMode(m) returns a command for WithCommands or Execution.Send. Acceptance fails with ErrInvalidCommand, and nothing is recorded, when the policy doesn’t authorize m or zelk can’t enforce it. An accepted change applies once no tool call is running; calls of the turn not yet decided see the new mode. Each change that alters the mode increments the policy revision. Entering or leaving plan mode changes the dynamic context, never the cached system prompt or tool list.
The model learns of a switch at working-assistant request boundaries. Each started attempt snapshots its effective mode. A request whose mode differs from that of the last request whose valid answer joined history gets a note after the history giving the net change, and the note is committed alongside the answer. Unobserved intermediate selections and net-zero cycles add no note. Failed or undispatched attempts, classifier calls, and portable or native compaction calls do not advance the baseline; after a compaction the rebuilt context names the current mode. A note entering plan mode carries plan mode’s instructions, and one leaving it says they no longer apply.
A mode’s guidance comes with it, as Claude Code
gives its model: plan mode carries its workflow (explore, design, check
against the request, write the plan in a fixed shape, present it with
ExitPlanMode when the session offers it), and auto mode its working rules
(proceed on reasonable assumptions, still confirm destructive steps, don’t
retry what the reviewer refused, finish the job); the rules that hold in every
mode, such as protecting uncommitted work, are in the system prompt. The guidance is a note after the history
on the first request in that mode, at the start of a session and after each
compaction, and on every switch into it; a note leaving plan mode says that
actions which change state run again. Subagents get none: they work on a
slice of their parent’s task. The text lives in core/internal/prompt
(plan.md, auto.md).
When an intermediate mode changes a tool’s permission outcome relative to the
assistant’s request mode, a call-specific harness note preserves the relevant
allow, denial, human approval or automatic review after the paired tool-result
group. Unaffected calls add no mode context. Invalidated approvals are still
decided afresh, including after a net-zero mode cycle. Policy revision and
approval reevaluation are audit bookkeeping, not model-facing notices; granting
a session rule can itself advance the revision without changing the mode.
Request snapshots and checkpoints preserve the baseline and pending decision
context. The complete command sequence, policy revisions, digests, classifier
bindings and enforcement are unchanged by what the model is told. Status.Modes
reports the modes a session authorizes, so a host offers only those.
Rule changes
Section titled “Rule changes”A host whose user changes the rules or protected paths while a conversation
runs sends Agent.RulesCommand() of the reconfigured agent (set_rules) to
its execution. It applies as a mode change does: once no tool call is
running, so the next call is decided under the new rules and a call already
running finishes under the old ones. The rules the user granted in the
session stay allowed, after the new ones, and a deny rule still overrides
them; removing a saved allow rule therefore doesn’t revoke the same rule
granted in the session. An approval asked before the change is bound to the
old policy revision: when answered, the call is decided afresh, so a new deny
refuses it whatever the answer. Each change that alters the rules increments
the policy revision. A subagent’s session refuses the command and keeps the
rules its parent gave it. An idle conversation takes the new rules at its
next start, whoever starts it: a launch takes them with the rest of the
setup (WithLaunchSetup), and any other start, such as a background
completion’s or a schedule’s wake, accepts a set_policy first when the
agent’s permission policy differs from the session’s, its grants and an
authorized mode kept (below). A start that changes nothing records nothing, so a deny rule
saved while a conversation is idle holds for the next run it makes, even one
nobody launched.
Narrowing
Section titled “Narrowing”An active host-trust skill’s allowed-tools join the allow rules while it is active (skills.md); a project-trust skill’s grant nothing. permission.Policy.Narrow is the only way a subagent gets a policy: the mode stays within the parent’s (plan < dont-ask < default < accept-edits, auto < bypass; accept-edits and auto don’t narrow to each other), authorized modes and tool ceilings are intersected, deny, human-only and ask rules and protected paths are combined, allow rules are the parent’s (or only those both have), and a wider request fails with permission.ErrWiden.
One-use classifier retry
Section titled “One-use classifier retry”A host or user can submit RetryDenied{action_digest, reason} for a retained
classifier denial through the Go command API, TUI /retry, or
zelk exec -retry-denied DIGEST resume --last "task". This requests another
review, not permission to execute. Tool output and the model cannot submit
this host command. The TUI /retry lists retained actions; Status.DeniedActions
and recorded PermissionDecided events expose their digests to other hosts.
Admission requires auto mode and a denial belonging to the current policy and review revisions. Unknown, stale and previously retried actions are refused before recording acceptance. The latest 128 distinct denials are retained; retirement makes an old action unavailable for override. Reasons in retained status are bounded to the classifier transcript entry limit.
CommandAccepted is the durable authorization: it marks that action retried,
arms its one-use classification, advances the review revision (invalidating
cached decisions) and removes only that action’s contributions from the
breaker window. Unrelated denials and the past trip count remain. The command
starts no run; send a user message when the model should propose the action
again. A replayed command ID acknowledges the original acceptance and cannot
arm another retry.
When the identical action reaches classification, deriving its pending effect consumes the armed retry. The effect carries the trusted override reason, so resume and attempt recovery review the same context. Classification keeps its normal timeout, cost bounds and retry limit. A failed/denied classification cannot authorize another override of that retained action. Normal verdict reuse still requires an exact action/policy/review match.
Every proposal first passes current hook and permission checks. Changing the mode or policy changes authorization and/or the action digest; an armed retry cannot bypass a tool ceiling, protected path, explicit deny or mandatory-human rule. Workspace changes and new model text do not broaden the authorized action.
Resuming a session
Section titled “Resuming a session”A session carries its conversation; each launch decides how it runs, as
Claude Code’s resume does. A host that takes a session up for a person
starts it with zelk.WithLaunchSetup(), and an idle root session then
records a ConfigChanged with the agent’s own setup: its policy (mode,
authorized modes, rules, protected paths, tool ceiling), run limits,
classifier and input configuration, and, with zelk.WithLaunchModel() for
a launch that named them, its model, provider and effort. zelk exec resume
does this, with exec’s plan default when no -mode is given, and so does
the TUI for a session it opens, on its first start.
The allow rules the user’s approvals granted for the rest of the session
(loop.State.Granted, every PolicyAmended rule) are kept after the
launch’s own, so “don’t ask again” lasts the session, and a deny rule of
the launch still overrides them. A configuration change that
changes the policy raises the policy revision, so an approval or retained
denial given under the old policy is decided again. A subagent’s session
keeps what its parent gave it, and a launch with the same setup records
nothing. Starts that aren’t launches (a wake, the next message, a rebuild
after an MCP change) keep the session’s setup, so a mode or model switched
within the session lasts, within the modes the agent authorizes (below).
Sessions that aren’t idle
Section titled “Sessions that aren’t idle”A launch replaces the whole setup only of an idle session: a run’s model,
limits and classifier can’t change under it. Its permissions can, since
every call is decided when it is made; set_rules already relies on that.
Without this, a session interrupted mid-run or waiting for an answer kept
the mode and modes it recorded on resume, so one started in bypass kept
bypass under a policy that forbids it, and a skill’s !`cmd` lines
in the resuming prompt were decided under the recorded rules before the
launch applied.
set_policy. A command carrying the host’s whole permission policy: mode, authorized modes, tool ceiling, rules, protected paths and whether skills may grant tools. It applies asset_rulesdoes, once no tool call is running or being decided by a hook (a hook’s allow, given under the old policy and hooks, would otherwise authorize the call under the new), keeps the session’s grants after the rules, raises the policy revision when it changes anything, and an approval asked under the old policy is decided afresh when answered. The session takes the command’s mode when the command is a launch’s, or when its own mode is no longer among the authorized ones; otherwise it keeps its mode, so a switch made within the session lasts.- Gate hooks follow the agent. A
set_policyalso carries the agent’s gate hooks, which replace the session’s when it applies, and a subagent’s continuation carries them too. The agent runs a hook by the name the session recorded, so one it doesn’t have, as under a managed policy’shooks: false, would fail every call’s gate closed. An idle launch’s setup carries them too. A hook invocation already pending when the session is taken up still runs by its recorded name, and the new policy waits for it. - A launch of a session that isn’t idle accepts a launch’s
set_policyfirst; the rest of the setup stays as recorded. An idle session’s launch is unchanged (ConfigChanged). - A start that isn’t a launch (a wake, the next message) accepts a
set_policywhen the agent’s policy differs from the session’s, in place of today’sset_rules, so a wake can’t run an old session in a mode the agent no longer authorizes. The session’s policy here is the one it will hold once its waiting changes apply, worked out by the reducer’s own apply step (loop.State.NextConfig): a start sends its own whenever that differs from what the start gives it, so no waitingset_rules, mode change orset_policyoutlasts it. A mode switch in the same start is checked against the modes itsset_policyauthorizes, not the recorded ones. - A skill’s shell lines are decided under the policy the start they
prepare for will apply:
Session.PromptandSession.InvokeSkillfold the session, accept thatset_policyin memory, and apply every change waiting, even when the start sends none. An idle root’s launch decides them under the setup the launch records, its classifier included. A host preparing a launch’s prompt says so (zelk.WithLaunchPolicy()); without it the lines are decided as a start that isn’t a launch would decide them. - Skill grants.
zelk.WithoutSkillGrants()records in the policy that no skill’sallowed-toolspre-approve anything, applied with the rest of the policy, so a skill already active in a resumed run loses its grants too. The host sets it under a managed policy’srules_only; it replaces skipping grants per skill source. - Calls not yet started. When a
set_policyis accepted and the only tool calls the session has asked to run never started, as when its host died between deciding them and starting them, they are taken back and decided again under the new policy, their hooks with them: a gate hook’s earlier allow doesn’t carry over. Nothing ran, as when an interrupt drops them. A call that started finishes under the policy it was decided by. - A session without a classifier isn’t given
autoby any start, since a start that isn’t an idle launch can’t record one: the agent drops it from the modes, and the mode becomes the narrowest left. A policy the session can’t take is an error, never skipped. - A subagent’s session keeps refusing
set_rulesand a replacingset_policy. When its parent resumes it, as with answers to its questions, it accepts a narrowingset_policy(Narrow): the reducer narrows its policy by the parent’s, aspermission.Policy.Narrowdoes, so it can never widen. The parent’s is the policy it holds once its own waiting changes apply. Two modes of equal rank that grant different things (acceptEditsandauto) narrow todefault, which is within both, and a child without a classifier is never givenauto. A child started directly, as a client loading it does, is narrowed by the policy its conversation’s root would take under the agent.