# Managed policy

A system-wide file that an administrator controls sets limits that the
user's config, the project's settings, flags and the live TUI can't widen.
It covers the permission modes allowed, a required sandbox, network reach,
permission rules and hooks. The reader is `cmd/zelk/internal/policy`.

## Where it lives

| OS | File | Drop-ins |
|---|---|---|
| Linux, WSL | `/etc/zelk/policy.json` | `/etc/zelk/policy.d/*.json` |
| macOS | `/Library/Application Support/zelk/policy.json` | `…/zelk/policy.d/*.json` |
| Windows | `%ProgramData%\zelk\policy.json` | `…\zelk\policy.d\*.json` |

- **Fixed paths.** Each OS has one fixed path. No flag and no environment
  variable can move it, because either would let a user skip the policy.
  `policy.Dir` returns it and `cmd/zelk`'s composition root passes it to
  `policy.Load`, so tests can pass another one. On Windows the folder is
  never taken from `%ProgramData%`, `%SystemDrive%` or any other variable,
  which the user sets for their own processes. zelk reads the machine-wide
  registry value the system names ProgramData from
  (`HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\ProgramData`,
  `%SystemDrive%\ProgramData`, writable only by an administrator) and
  replaces `%SystemDrive%` with the drive of the system's Windows directory
  (`GetSystemWindowsDirectory`), which no process can change. A value that
  names any other variable is refused. If the system can't name the folder,
  zelk refuses to start. `SHGetKnownFolderPath(FOLDERID_ProgramData)` reads
  the same value but expands `%SystemDrive%` from the caller's environment,
  so it can't be used: measured in child processes on Windows 10.0.26300,
  it returned `C:\ProgramData` with `SystemDrive=C:` and failed with the
  variable missing or pointing at a drive with no `ProgramData`, so it
  follows whatever drive the variable names.
- **Drop-ins.** The main file is read first, then each `*.json` drop-in in
  name order (`10-network.json`), which lets separate tools manage
  separate concerns. Merging works as in Claude Code:
  - Lists are unioned.
  - A drop-in's scalar replaces the earlier one.
  - Within a limit, the stricter value doesn't win automatically; the
    last file read sets it.
- **Owned by root.** Each file, and the folder holding it, must be owned
  by root and writable by nobody else. A file the user could edit isn't a
  policy, so zelk won't start and says why. This differs from Claude Code,
  whose docs don't check ownership. On Windows, "root" is the system's
  administrators, and "writable by nobody else" is a judgment of the
  security descriptor: see [Trust on Windows](#trust-on-windows).
- **Fails closed on what it can't read.** zelk refuses to start when a
  file isn't valid JSON, holds a value zelk can't use (`"sandbox":
  "maybe"`, a malformed rule) or can't be read. The error names the file.
  A missing file means no policy.
- **Warns on keys it doesn't know.** A key zelk doesn't know, such as a
  limit from a newer zelk or a misspelling, is skipped with a warning
  that names the file and the key, as Claude Code skips it. The warning
  is hard to miss: a notice in the TUI, a line on stderr from `exec` and
  `-p`, a line in `zelk acp`'s log, and a list in `zelk policy`.
- **Read once at start.** A changed policy takes effect when zelk next
  starts. Claude Code polls its sources; zelk doesn't need to, because a
  session never runs long enough to miss a policy change that matters.

## Trust on Windows

Go reports a Windows file as 0o666 or 0o777 whatever its ACL says, and
Windows has no single "root" owner, so the Unix check can't be reused. The question is the
same, though: could anyone but an administrator change the policy, or move
it away? Each object is judged from its security descriptor, read from the
handle zelk opened.

**Who is trusted.** SYSTEM (`S-1-5-18`), the Administrators group
(`S-1-5-32-544`) and TrustedInstaller (`S-1-5-80-956008885-…`). Nobody else:
not the user who runs zelk, not Users, Everyone or Authenticated Users. The
placeholders CREATOR OWNER and OWNER RIGHTS count as trusted in an ACE
because the owner is judged separately.

**What is judged**, for the policy folder, `policy.d`, and each policy file:

1. *The owner is trusted.* An owner can always rewrite the object's DACL,
   whatever the DACL says, so an owner who isn't trusted is another
   principal with full control. This is also why a folder a standard user
   makes in `%ProgramData%` is refused: `%ProgramData%` grants Users the
   right to create folders and files (read from `C:\ProgramData` with
   `icacls` on Windows 10.0.26300: `BUILTIN\Users:(CI)(WD,AD,WEA,WA)` and
   `CREATOR OWNER:(OI)(CI)(IO)(F)`), the creator becomes the owner, and the
   new folder inherits Users' create rights besides.
2. *The DACL isn't null.* A null DACL gives everyone full access.
3. *No other principal holds a write-like right*, in any ACE that applies to
   the object, inherited or explicit: `FILE_WRITE_DATA` (add a file to a
   folder, or change a file), `FILE_APPEND_DATA` (add a subfolder, or append),
   `DELETE`, `WRITE_DAC`, `WRITE_OWNER`, `GENERIC_WRITE`, `GENERIC_ALL`, and,
   on a folder, `FILE_DELETE_CHILD` (remove or rename its entries). Inherited
   entries count because Windows enforces them like any other; the message
   says when one was inherited.
4. *Deny entries are ignored.* They only take rights away, and weighing one
   against an allow entry means knowing who is asking. An allow entry a deny
   entry masks is still refused. An entry that applies only to children
   (`INHERIT_ONLY`) doesn't count against the folder, but does against a file
   that took it. An ACE type zelk can't judge is refused rather than guessed
   at.

**The folders above.** Each folder from the drive's root down to the policy
folder must be owned by someone trusted and must give no one else
`FILE_DELETE_CHILD`, `DELETE`, `WRITE_DAC`, `WRITE_OWNER` or `GENERIC_ALL`:
whoever could remove or rename `%ProgramData%\zelk`, or a folder above it,
would turn the policy off, since a missing folder is no policy. Creating
entries in a parent is harmless, so Users' create rights on
`%ProgramData%` are fine there. The default `C:\` and `C:\ProgramData` pass
(read on the same system, and tested on every Windows run).

**Handles, not paths.** Each object is opened with
`FILE_FLAG_OPEN_REPARSE_POINT` and the opened handle is judged with
`GetSecurityInfo` and `GetFileInformationByHandle`; a policy file is read
from the handle that was judged. An object that is a reparse point of any
kind (a symbolic link, a junction, a cloud placeholder), or a folder above
the policy that is, is refused: a link names another object, and the policy
must be the one at its path. A swap between the check and the read can't
substitute another object, and the trusted folders can't be changed by
anyone untrusted in the meantime. A path on a network share is refused,
since zelk can't vouch for what the server lets users do, and so is a file
system that keeps no ACLs.

**When the folder is missing** (or a folder above it), there is no policy, as
on Unix. **When it is present but untrusted**, zelk refuses to start, and the
message names the object and what is wrong with it: the owner's account and
SID, or the principal, the rights and whether they were inherited. A folder
that Users can't read is refused too, since zelk couldn't read the policy as
a standard user.

**Setting it up.** In an elevated PowerShell (`New-Item` as an administrator
makes a folder Administrators own, but one that inherits Users' create
rights from `%ProgramData%`, which is refused until inheritance is removed):

```powershell
$dir = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'zelk'
New-Item -ItemType Directory -Path $dir -Force | Out-Null
icacls $dir /inheritance:r
icacls $dir /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' '*S-1-5-32-545:(OI)(CI)RX'
# ... create policy.json (and policy.d) here, then:
icacls $dir /setowner '*S-1-5-32-544' /T
icacls $dir            # SYSTEM and Administrators full, Users read; nothing else
```

Use `zelk policy` to confirm it is read.

**Verified.** The rules on descriptors are unit-tested everywhere
(`descriptor_test.go`). The reading of real descriptors, links and the file
opening are tested on NTFS without an administrator
(`trust_windows_test.go`: Windows 10.0.26300, through `scripts/wintest`),
with the test's user as the extra owner `Load` takes for tests. Real
Administrators ownership is tested only by `scripts/windows-admin-tests.ps1`
(tag `admin`), run from an elevated PowerShell. The tests make a stand-in for
`%ProgramData%` in their own folder at the root of the system drive and never
touch the real `%ProgramData%\zelk`.

## What it sets

```json
{
  "modes": ["plan", "default", "accept-edits"],
  "sandbox": "required",
  "network": "allowlist",
  "network_allow": ["github.com", "*.npmjs.org"],
  "deny": ["Bash(curl *)", "Read(**/.env)"],
  "ask": [], "human": ["Bash(git push *)"], "protect": ["infra/**"],
  "allow": [],
  "rules_only": false,
  "hooks": false,
  "client_terminal": false,
  "credential_store": "keychain"
}
```

| Key | Effect |
|---|---|
| `modes` | The only permission modes zelk may start in or switch to. It applies to every way of changing mode: `-mode`, the TUI's saved start mode, shift+tab, a plan's approval, ACP `set_mode`, and subagents, whose modes already narrow within their parent's. Leaving out `bypass` and `auto` is the usual reason to set this. |
| `sandbox` | `"required"`: commands run under bwrap (Linux), seatbelt (macOS) or MXC (Windows). `"optional"` lifts a requirement an earlier file set. On Windows, run `zelk sandbox setup` and agree to [Microsoft's MXC telemetry](/internals/enforcement/#telemetry). If the platform launcher cannot be used, the host fails startup. |
| `network` | The widest network commands may reach: `"off"`, `"allowlist"` or `"full"`. Under `"allowlist"`, the user's allowed hosts must fall within `network_allow`. A limit narrower than `"full"` also requires a sandbox, since only a sandbox holds commands to it. A managed allowlist requires bwrap’s enforced network boundary. On macOS and Windows, `"allowlist"` limits network mode to `"off"`. |
| `network_allow` | The hosts a user's allowlist may name. A host's own egress (web tools, HTTP MCP) obeys the same list. |
| `deny`, `ask`, `human`, `protect`, `allow` | Rules added to every session. Policy rules are combined with everyone else's, and the strongest match wins, as for every other source. So a policy `deny` can't be undone by any `allow`, and a policy `human` rule always asks a person. |
| `rules_only` | `true`: only the policy's `allow` rules count. The user's, the project's and the flags' `allow` rules are dropped; their deny, ask and human rules still apply, since those can only narrow. This is Claude Code's `allowManagedPermissionRulesOnly`. |
| `hooks` | `false`: the user's `hooks.json` and the project's `.zelk/hooks.json` don't run. A `PermissionRequest` hook can answer "allow" at the human gate, so a policy that holds a human rule must also be able to switch hooks off. |
| `client_terminal` | `false`: ACP's `-client-terminal` is overridden, with a warning. It runs commands in the editor's terminal, outside zelk's sandbox. |
| `credential_store` | `"keychain"`: credentials are kept in the system keychain. A user's `file` is overridden, with a warning; a document still in a file, and an API key typed into `providers.json`, is refused until `zelk credentials move -to keychain` moves it. `"any"` lifts a requirement an earlier file set. See [keychain](/internals/keychain/#managed-policy). |

**Unset keys don't limit anything.** An empty policy changes nothing.

**Not yet implemented:** MCP server allow and deny lists, model
allowlists, forced login or provider, `env`, a minimum zelk version, and
server-delivered or MDM policy.

## How it applies

**The policy always wins. A setting the user never chose is moved inside
it without comment; one the user did choose is overridden with a
warning naming both values and the policy file**, as Claude Code's
managed settings override without stopping the launch.

- The sandbox defaults to `none`. Under a policy with `"sandbox":
  "required"`, a user who never set it gets bwrap or seatbelt.
- A user who passes `-sandbox none`, or has `"sandbox": "none"` saved in
  `config.json`, gets bwrap or seatbelt too, and a warning: *-sandbox
  none overridden: the policy at /etc/zelk/policy.json requires a
  sandbox*.
- A `-mode`, or a saved TUI start mode, the policy doesn't allow becomes
  the first allowed mode, with the same kind of warning. A script that
  passed `-mode bypass` may then find commands refused that no one is
  there to approve; the warning on stderr says why.
- Where the warning goes: a notice in the TUI, a line on stderr from
  `exec` and `-p`, a line in `zelk acp`'s log.

Where it is enforced:

1. **In the host, when config is resolved (`host.Flags.Settings`).**
   After flags and saved defaults are merged, the policy moves what falls
   outside it inside, and says so for what the user chose.
2. **In `wire`, where project rules are merged.** The policy's rules go
   in here. `rules_only` drops the `allow` rules from the other sources,
   and `hooks: false` drops their hooks. Every start gives a session
   the agent's gate hooks, so a session recorded with the user's hooks
   runs without them too
   ([permissions](/internals/permissions/#sessions-that-arent-idle)).
3. **Where each host lists the modes it authorizes.** The TUI's
   shift+tab cycle, ACP's modes and a plan's approval choices are each
   intersected with `modes` before they become `WithAllowedModes`.
   Core's `CheckModeChange` already refuses any mode outside that list,
   from every source including ACP's `set_mode`, and a resumed session
   takes the launch's modes, so a session started before the policy
   can't keep bypass. Over ACP, a session's first run in the process is
   that launch, so one an editor loads takes them too. A session
   interrupted mid-run or waiting for an answer takes the policy's
   permissions too, through `set_policy`, and a skill's shell lines in
   the resuming prompt are decided under them
   ([permissions](/internals/permissions/#sessions-that-arent-idle)).
4. **`rules_only` and skills.** A skill's `allowed-tools` are allow rules
   by another name, so under `rules_only` the host gives the agent
   `WithoutSkillGrants`: no skill pre-approves anything, in new sessions,
   resumed ones and their subagents.

Allow rules a person grants in a session ("always allow this") still
count under `rules_only`: a person approved each one. A subagent keeps
the policy its parent was given.

Because the TUI's live settings go through `Settings` and `wire` again,
a live change is held to the same policy.

## How users see it

- **TUI Settings.** A row set by policy shows its value with "· policy"
  and can't be changed. Choices the policy rules out (`None` under
  Sandbox, `bypass` in Starting mode) aren't offered.
- **TUI mode switching.** Shift+tab cycles only through the allowed
  modes.
- **Warnings** for skipped keys and overridden settings, as above.
- **`zelk policy`.** Prints the files read and the limits in force, in
  both text and `-json`. Support staff ask for its output first.

## Testing

- **Unit tests** for reading and merging: drop-in order, unions, unknown
  keys warned about, invalid JSON and bad values refused, root ownership and mode bits
  checked, with the ownership check injected. On Windows, the decision on a
  descriptor is tested on its own (every refusal and acceptance, on any
  system); real descriptors, links and file opening are tested on NTFS; the
  Administrators-owned case needs the elevated script.
- **Host tests:**
  - each limit against a flag, a saved default and a project setting;
  - an unset value moved inside the policy silently, a chosen one with a
    warning;
  - `rules_only` dropping allow rules;
  - `hooks: false` dropping user and project hooks.
- **Live-settings tests:** policy rows locked, and the forbidden choices
  missing.
- **Core:** `CheckModeChange` with ACP `set_mode` to a mode the policy
  rules out.
- **Live check:** a scratch policy under a temporary root (the path
  injected in tests; in tmux, a build with the path passed in), with the
  TUI, `exec` and `acp`.
