# Execution authority and sandbox

| Check | Answers | How |
| --- | --- | --- |
| Authority | Who is asking | Authenticated principal and a fixed capability ceiling on every request; nested Agents never widen it |
| Permission | May this operation run | One shared decision under the execution branch's mode; the mode can change mid-turn and the next tool check uses it. See [Permission decision and refusals](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/security/permission-decision.html). |
| Sandbox | What an approved process can touch | Seatbelt (macOS) or bubblewrap (Linux). Off unless the Sandbox switch of the conversation branch the turn runs on is on. |

The same contract covers Web, CLI, ACP, channels, nested Agents, scheduled tasks and continuation.

## Authenticated authority

| Case | Rule |
| --- | --- |
| Authenticated local entry | Attaches complete owner authority to `TurnRequest` before durable admission. The audit actor and the execution request are separate values; an admission actor alone does not authorize tools. |
| Paired channels | Keep the paired tier |
| Nested requests | Inherit, cannot expand |
| Missing or unknown authority | Fails closed with a stable reason code |
| Recovery | Never rebuilds owner authority from a source label or model text. Legacy admitted requests without authority must be resubmitted through an authenticated entry. |

## One operation decision

The approval manifest and the execution wrapper use the same decision.

| Case | Rule |
| --- | --- |
| Owner-delegated Agent shell and managed processes | Use the admitted permission snapshot, not a blanket source prohibition |
| MCP callers, non-owner spawned Agents | Keep that prohibition; worktree controls keep their own restriction |
| Bypass permissions | Skips ordinary approval and Auto classification. Does not override explicit ask or deny rules or plugin tool gates. With Sandbox on, commands stay sandboxed. |
| Invalid mode values | Rejected by configuration commands |
| Denials | Name their reason and capability without exposing secrets |
| Web answers | The question and selected answer stay until the canonical wait command is acknowledged as applied. Unknown delivery locks the selection and retries the same command identifier; a socket send alone is not completion. Covers approvals, questions, forms and discussion. |

### Delegated checks and audit privacy

| Item | Rule |
| --- | --- |
| Write and edit targets | Spawned-Agent and MCP calls need a nonblank string target. An explicit empty patch target is denied before Bypass permissions and allow rules. |
| Relative targets | Resolved against the bound worktree; realpath containment includes file and parent-directory symlinks. The shared file-safety helper keeps its current-directory semantics for standalone relative inputs. |
| `security.risky_tool_delegated` | Delegated risky-tool check admitted by Bypass permissions or an allow rule |
| `security.path_violation` | Denied write target |
| Event meaning | Permission checks, not completed execution; may repeat during manifest construction or reconciliation |
| Payload | Session, tool, source, authority and a fixed reason. No commands, code, target paths or other argument text. Origin `system`; existing event-log routing and rotation. |
| Delivery | Best effort; never authorizes or blocks |

## Mode resolution

The setting of the conversation branch the turn runs on, then the project's default, then Bypass permissions (`DEFAULT_PERMISSION`). The resolved mode drives admission and UI acknowledgements. [The modes](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/security/permission-decision.html#modes) are defined with the decision.

## Live permission changes

| Aspect | Rule |
| --- | --- |
| State | `SessionStore` owns a versioned `permission_state` dictionary per branch, with mode and owner principal. Atomic compare-and-set stops stale clients overwriting a newer selection. No parallel approval database or generic policy engine. |
| Settings command | WebSocket; authenticates the owner, validates session and branch scope, returns the authoritative mode, version and branch identity. Conflicts stay errors. |
| Takes effect | At server confirmation, independent of an in-flight model request. Each later ordinary approval check uses it, including later calls in the same batch. One call keeps its decision through dispatch; authorized calls are not interrupted. No restart or next message needed. |
| Web and App | Send immediately with the confirmed version, reading first only when none is known. A requested selection is shown apart from an acknowledged mode; older acknowledgements and hydration snapshots cannot replace newer state; transport errors stay visible. |
| Unsent draft | Stores its selection locally without creating a session; first submission supplies it |
| Open approvals on a mode change | Re-evaluated with the shared decision. Now allowed: resolved through the canonical wait-answer command and resumed from its checkpoint. Ask rules, outbound holds, Sandbox escalation and user questions keep waiting. |
| Races and restart | A wait published during a settings change rechecks after the old runtime releases its cancellation token. Startup recovery re-evaluates persisted changes. Expired, cancelled or completed work is never resurrected. |
| Spawned Agents | At trusted spawn admission a running owner parent passes its effective mode and rules into the child's immutable input, bound to the same principal and exact runtime parent. An interactive parent resolves its latest confirmed mode first; a nested non-interactive parent passes its frozen snapshot. Existing inputs are not rewritten. Children stay non-interactive: an ask with no approver denies; inherited Bypass permissions skips only ordinary approval. |
| Excluded from live overrides | Standalone scheduled tasks, paired channels, unrelated sessions |
| Plan | Enforced at the tool boundary, so switching in blocks writes already proposed. A stable tool catalog allows switching out mid-turn without invalidating continuation. Entered only from the selector; `exit_plan_mode` restores the previous mode. |
| Stored mode | An existing `permission_mode` is readable when no versioned state exists |
| One-shot approvals | Self-update and operations with no representable exact rule offer only a single allow; canonical validation enforces the same scope list. Answers count once the server acknowledges them; execution versions must match after a reload; the service owns the allowed scopes. |

## Tool and host boundaries

| Surface | Boundary |
| --- | --- |
| File tools | In-process guards |
| Local subprocesses | Seatbelt or bubblewrap |
| Browser, Web Use | Exact surface grant |
| Docker, SSH | Their own execution boundary |
| Configured MCP processes | Owner-configured trust, not local sandbox isolation |

| Setting | Effect |
| --- | --- |
| `workspace-write` | Writes to working roots, masks protected reads, filters credential environment variables, network off unless `sandbox.network` |
| `danger-full-access` | Host user permissions |
| Missing backend | Refuses by default; explicit `warn` is an acknowledged fallback |
| Sandbox switch | A branch override resolved into an immutable turn snapshot. A change affects later turns, not current processes, other sessions, scheduled tasks or inherited child policy. Ordinary approval never disables it. |
| Scheduled commands and prompts | Use their conversation's setting when they fire |

### Protected writes

A sandboxed command escapes by writing a file that something outside the sandbox runs later. The worker starts in home, so a conversation with no project folder has home as its writable root. `host/sandbox/protected_writes.py` keeps these read-only on top of every policy; no configuration removes them.

| Scope | Paths |
| --- | --- |
| By name, anywhere | `.bashrc` `.bash_profile` `.bash_login` `.profile` `.zshrc` `.zprofile` `.zshenv` `.zlogin` `.gitconfig` `.gitmodules` `.ripgreprc` `.mcp.json` `.vscode/` `.idea/` `.claude/settings.json` `.claude/settings.local.json` `.claude/commands/` `.claude/agents/` `.claude/hooks/` |
| Home folders | `~/.ssh` `~/Library/LaunchAgents` `~/.config/autostart` `~/.config/systemd` `~/.config/git` `~/.claude`, and every OpenProgram state folder, whose config could turn the sandbox off next turn. A writable root inside one (a session worktree) stays writable; the name rules still apply inside it. |
| Starting repository | Its `.git/hooks` and `.git/config`. Only that existing repository, so `git init` and `git clone` keep working. |

- **macOS**: Rules are patterns in the Seatbelt profile
- **Linux**: bubblewrap mounts only existing paths read-only: the home folders, named files at the top of each writable root and of home, the repository's git paths. A protected name created later deeper in the workspace is not covered.
- **In-process write tools**: Same rules through `validate_write_path`
- **Lifted by**: An approved escalation (writable root `/`), for that command

**Why not Anthropic's sandbox-runtime**

The list follows its mandatory deny paths. Measured as a macOS replacement and not adopted; its process boundary matches ours, so only the list was taken.

| Cost | Measured |
| --- | --- |
| Startup | A Node program, so every command starts Node: about 120 ms against about 10 ms for direct Seatbelt |
| Packaging | The packaged runtime would ship Node and ripgrep |
| Git | Denies `.git/config` in every repository, which breaks `git init` |

## Sandbox escalation

Requested before the command runs, as in Codex: `bash` with `sandbox_permissions="require_escalated"` and a justification.

| Aspect | Rule |
| --- | --- |
| Card | Manifest for `bash:sandbox-escalation` at the Agent safe point, ahead of any effect; it covers what an ordinary ask would have asked |
| Who approves | Only an interactive local owner with `approval.request`. Outside Bypass permissions, paired channels, MCP clients, cron and subagents cannot escalate. |
| Lifts | Configurable restrictions; credential filtering stays |
| Binding | Session, execution, tool and tool call; a normal tool approval cannot authorize it |
| Conversation scope | The exact command in worker memory, never a permission rule, so a restart asks again |
| No sandbox in force | The request is ignored |
| Bypass permissions | Leaves the sandbox without a card |
| Denial seen after the run | Access markers, or name-resolution and unreachable-network errors with `sandbox.network` off, never become a late approval. The result names the request to make. |

## Approved file writes

Approved edit, write and apply_patch share `file_state.write_checked`. The dispatcher and this module import on Windows without Unix-only modules.

| Aspect | Rule |
| --- | --- |
| Sequence | Check approved content and identity; open without truncation; take the exclusive lock; hash the opened descriptor; recheck pathname identity and resolved destination; write |
| Locks | Existing compatibility adapter (`fcntl` on Unix, `msvcrt` byte locks on Windows), binary mode; POSIX keeps `O_NOFOLLOW`. Removing link checks or skipping locks does not meet the contract. |
| Revalidation | Uses metadata, not a second read handle: Windows byte locks can deny reads through another handle in the same process |
| Links | Symlinks and reparse entries rejected |
| Missing targets | Exclusive creation |
| Path fallback | Detects replacements before writing; does not claim descriptor-relative protection against every concurrent ancestor replacement |

## Failures and known limits

- Missing authority, stale versions, invalid modes, denied capability, explicit rules, classifier failure and sandbox refusal stay distinguishable. No failure silently becomes owner or Bypass permissions.
- Host process visibility may block `ps`, `top` or `lsof`. Docker sockets are not exposed automatically. Linux wildcard masking has limits. Browser and remote networking have separate controls.

**Files**

| Module | Responsibility |
| --- | --- |
| `permissions/authority.py` | Identity and capability ceilings |
| `permissions/state.py` | Versioned branch state, owner validation, atomic updates |
| `permissions/policy.py` | Shared decisions and explicit rules |
| `permissions/auto_mode/classifier.py` | Auto risk classification; only JSON boolean `true` permits execution |
| `permissions/approvals/approval.py` | Approval manifests, exact wait consumption, tool execution |
| `permissions/approvals/lifecycle.py` | Live call snapshots, canonical wait reconciliation |
| `conversation/session_settings/session_config.py` | Legacy and current settings resolution |
| `conversation/production_driver/` | Durable admission, immutable recovery, wait publication |
| `interfaces/server/ws_actions/permissions.py` | Authenticated settings, canonical wait re-evaluation |
| Web permission state and composer | Confirmed mode, pending and error feedback, ordered hydration |

**Acceptance**

- Live changes: chat admission and a safe tool; inherited Bypass permissions; running ask-to-Bypass permissions and back; waiting approval continuation; explicit ask and deny; Plan transitions; owner and session isolation; stale versions; reload and reconnect; unchanged Sandbox denial.
- File writes: dispatcher import without `fcntl`; changed or deleted targets; existing and new files; exact UTF-8 bytes; replacement and link races; repeated writes. The Windows installation smoke imports the dispatcher; platform CI runs the approval regressions before the unit suite.

**How other frameworks compare**

| Framework | Adopted or adapted | Boundary |
| --- | --- | --- |
| Claude Code | Permission modes, independent Sandbox, Auto classification | Authority and explicit rules stay ahead of Bypass permissions. Its [permissions](https://code.claude.com/docs/en/permissions) have deny-before-ask-before-allow, live rule changes and per-approval comments; approval comments that execute first and deliver feedback afterward are not implemented here. |
| Codex CLI | Structured violations, exact approved retry. [Sandbox enforcement separate from approval policy](https://openai.com/index/running-codex-safely/). | No per-tool sandbox override. Its remembered approval is session-level; ours is project-scoped. Domain policy, managed enterprise enforcement and remote audit export have no equivalent here. |
| OpenClaw | Credential filtering, backend refusal, nested tool classification | No automatic Docker selection |
| Hermes Agent | Hard rules before bypass, command normalization, non-interactive refusal | Normalizes NFKC, ANSI, NUL and environment wrappers |
| OpenCode | Per-tool and per-resource rules | Permission is not OS isolation. [V2](https://opencode.ai/v2/docs/permissions) uses last-match order, project-scoped patterns, same-session rejection fan-out and per-subagent policy; ours is deny-first, exact-operation grants, one canonical wait target, child admission bounded by the parent. Deliberate differences. |
| pi-mono | Extension interception, fail-closed non-interactive behavior | Rejects silent project overrides of global security constraints |
| Aider | Git recovery as a separate facility | Recovery does not replace credential, network or process boundaries |
| Goose, WeClaw adapters | Explicit backend distinctions | Rejects external automatic owner approvals and optional isolation presented as default |

Each framework as it was studied, not its latest upstream version.

## Implementation status

| Area | In place |
| --- | --- |
| Decision | Authority on every entry, the shared decision, five modes with versioned live changes, delegated checks and audit events |
| Isolation | Seatbelt and bubblewrap isolation, exact escalation, approved file writes |
| Approvals | Survive an App reload with the same options; a single-use approval completes its operation; a decline ends the execution without starting a managed process |
| Input | All composer presentations submit through one acknowledged hook; the question tool declares its durable wait before execution |

| Area | Open |
| --- | --- |
| Windows | Approved file writes pass local regressions; native x64 and arm64 execution not verified; no process sandbox |
| Question waits | End-to-end acceptance of the durable declaration |
| Rule persistence | The permanent rule-save failure path is not exercised by filesystem failure injection |
| Not implemented | Domain and port network allowlists (need a managed proxy and redirect checks), resource quotas, per-tool sandbox overrides, a complete background Auto-classifier interface |
