Skip to content
Python

feat(auto-approve): inert, reversible writes inside the workspace run without a reviewer call (OPE-233)

Devika Verma9a5dfc2e7b78
diff --git a/coworker/agent.py b/coworker/agent.py
index edb3a970..7199032b 100644
--- a/coworker/agent.py
+++ b/coworker/agent.py
@@ -602,6 +602,7 @@ def build_engine(
risk_overrides=override_store.resolver(),
trust_overrides=override_store.trusted,
grant_trust=override_store.set_trust,
+ inert_writes=str(config.auto_approve_inert_writes),
)
# The plan-mode exit door — mutually exclusive with the board's decomposition
# gate, DERIVED from the team trait (owner call 2026-08-16): a lead never
diff --git a/coworker/config.py b/coworker/config.py
index 02eb4a32..9f826caf 100644
--- a/coworker/config.py
+++ b/coworker/config.py
@@ -87,6 +87,11 @@ class Config:
# gates (zero false-allows; ≥30% fewer prompts) get measured on real sessions. Costs
# one model call per card while on. Off by default; user-global only.
auto_approve_shadow: bool = False
+ # Auto-Approve gate tier (OPE-233): an inert, reversible write inside the session's
+ # folders runs without a reviewer call. "off" (default) | "audit" (record what it
+ # would have allowed, change nothing) | "on". User-global only: a cloned repo must
+ # not be able to hand itself a looser gate.
+ auto_approve_inert_writes: str = "off"
host: str = "127.0.0.1"
port: int = 8765
# Web search provider: "duckduckgo" (keyless default) | "you" (keyless, optional key)
@@ -158,6 +163,7 @@ _FIELDS = {
"allowed_domains",
"auto_approve",
"auto_approve_shadow",
+ "auto_approve_inert_writes",
"host",
"port",
"web_search_provider",
@@ -184,6 +190,7 @@ _GLOBAL_ONLY_FIELDS = {
"allowed_domains",
"auto_approve",
"auto_approve_shadow",
+ "auto_approve_inert_writes",
}
_WORKSPACE_FIELDS = _FIELDS - _GLOBAL_ONLY_FIELDS
diff --git a/coworker/engine.py b/coworker/engine.py
index 29e94a68..cbda1fa7 100644
--- a/coworker/engine.py
+++ b/coworker/engine.py
@@ -302,6 +302,10 @@ class TurnEngine:
# the card and in the reviewer's request. Runtime-only, like `_ask_replies`: a
# restart costs context (more cards), never correctness.
self._agent_files = provenance.SessionFiles(permissions.workspace_root)
+ # The inert-writes tier (OPE-233) may rewrite a file the agent itself wrote: only
+ # the agent's own bytes are lost. An injected lookup (tests) is left alone.
+ if getattr(permissions, "agent_wrote", None) is None:
+ permissions.agent_wrote = self._agent_files.wrote
self._tool_result_max_bytes = (
toolresult.DEFAULT_TOOL_RESULT_MAX_BYTES
if tool_result_max_bytes is None
@@ -1616,6 +1620,22 @@ class TurnEngine:
human_only=True,
)
+ # OPE-233: an Auto-Approve gate tier let this call run without the reviewer —
+ # recorded, never invisible (transcript chip + audit row), like every other
+ # cardless origin.
+ if allowed and decision.tier:
+ self._approval_origins[tool_call.id] = {"origin": "gate_tier", "note": reason}
+ self._audit(tool_call, stage="auto_allowed", status="allowed", reason=reason)
+ elif decision.tier and decision.tier_audit_only and decision.needs_user:
+ # Audit mode: the decision is unchanged; the record notes what the tier WOULD
+ # have done, so it can be measured before anyone switches it on.
+ self._audit(
+ tool_call,
+ stage="gate_tier_shadow",
+ status="would_allow",
+ reason=f"{decision.tier}: {decision.tier_note}",
+ )
+
if allowed and decision.rule:
# A task-scoped standing rule auto-allowed this call: audit the exact rule
# (§25 invariant — every auto-allowed call cites its rule) and remember it so
diff --git a/coworker/permissions.py b/coworker/permissions.py
index 53ff0734..a5f28639 100644
--- a/coworker/permissions.py
+++ b/coworker/permissions.py
@@ -479,6 +479,11 @@ from .risk import ( # re-exported for back-compat (manager.py imports WRITE_TOO
classify,
is_consequential,
)
+from .workspace_safety import inert_write_check
+
+# The reason prefix of an OPE-233 inert-write allow; the engine keys the transcript chip
+# and the audit row on `Decision.tier`, this text is what the record says.
+INERT_WRITE_REASON = "inert, reversible write inside your folders"
# The transcript's full Auto-Approve explainer (owner copy 2026-08-24). Persisted as a
@@ -577,6 +582,12 @@ class Decision:
site: str = ""
# The "host:port" entries a `request_network_access` call still needs a person for.
network_hosts: tuple[str, ...] = ()
+ # Set when an Auto-Approve gate tier matched (OPE-233), e.g. "inert_write". With
+ # `allowed` the call runs without the reviewer; with `tier_audit_only` the decision is
+ # unchanged and the engine only records that the tier WOULD have allowed it.
+ tier: str = ""
+ tier_audit_only: bool = False
+ tier_note: str = ""
def standing_rule_candidate(
@@ -693,6 +704,12 @@ class PermissionEngine:
# `workspace_root` is the sole writable root (back-compat). Kept by reference and re-read on
# every check, so runtime add/remove of folders takes effect without rebuilding the engine.
roots: Optional[list] = None
+ # OPE-233 gate tier, Auto-Approve only: "off" (default), "audit" (record what it would
+ # have allowed, change nothing) or "on". User-global config, never a workspace's.
+ inert_writes: str = "off"
+ # "Did the agent's own write produce this file this session?" — the engine's
+ # provenance record. A file the agent wrote can be rewritten without losing the user's.
+ agent_wrote: Optional[Callable[[Path], bool]] = None
def __post_init__(self) -> None:
self.workspace_root = Path(self.workspace_root).expanduser().resolve()
@@ -701,6 +718,8 @@ class PermissionEngine:
self.roots = [{"path": self.workspace_root, "writable": True}]
if self.shell_kind is None:
self.shell_kind = "powershell" if sys.platform == "win32" else "bash"
+ if self.inert_writes not in ("off", "audit", "on"):
+ self.inert_writes = "off"
def _resolved_roots(self) -> list[tuple[Path, bool]]:
out: list[tuple[Path, bool]] = []
@@ -947,6 +966,22 @@ class PermissionEngine:
if self.mode is Mode.CUSTOM and tool_name in self.auto_allow_tools:
return Decision(True, "auto-allowed by config")
+ # OPE-233: in Auto-Approve, an inert write that can be undone needs no reviewer
+ # call. It is the last check on purpose: every floor above (folders, protected
+ # files, self-protection, read-only modes) has already had its say.
+ if is_write and self.mode is Mode.AUTO_APPROVE and self.inert_writes != "off":
+ paths, _located = write_paths(tool_name, arguments) # located: checked above
+ eligible, detail = inert_write_check(
+ arguments, [self._candidate(p) for p in paths], agent_wrote=self.agent_wrote
+ )
+ if eligible and self.inert_writes == "on":
+ return Decision(True, f"{INERT_WRITE_REASON}: {detail}", tier="inert_write")
+ if eligible:
+ return Decision(
+ False, "requires approval", needs_user=True,
+ tier="inert_write", tier_audit_only=True, tier_note=detail,
+ )
+
# Otherwise: ask the user.
return Decision(False, "requires approval", needs_user=True)
diff --git a/coworker/provenance.py b/coworker/provenance.py
index 0c495be6..8496c4d1 100644
--- a/coworker/provenance.py
+++ b/coworker/provenance.py
@@ -249,6 +249,12 @@ class SessionFiles:
# ones that would execute.
self._files[key] = Origin(step=step, kind=origin)
+ def wrote(self, path: Path | str) -> bool:
+ """True when the agent's own write (not a download) produced this file's current
+ bytes this session. Overwriting it loses nothing of the user's (OPE-233)."""
+ origin = self._files.get(resolve(str(path), self.root))
+ return origin is not None and origin.kind == WRITTEN
+
@staticmethod
def _is_device(path: str) -> bool:
try:
diff --git a/coworker/workspace_safety.py b/coworker/workspace_safety.py
new file mode 100644
index 00000000..1935c6a4
--- /dev/null
+++ b/coworker/workspace_safety.py
@@ -0,0 +1,167 @@
+"""What code can establish about a workspace write without asking a model (OPE-233).
+
+Auto-Approve lets a write skip the reviewer when undoing it is easy and nothing about it
+can execute later: an inert file type, a name and content that don't look secret, and a
+target that is new, git-tracked with no uncommitted changes, or written by the agent
+earlier in this session. Every check fails toward "ask the reviewer": an unknown file type,
+an unreadable git state or a doubtful name keeps today's behaviour.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import subprocess
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+# Documents, data and media. Nothing here is loaded and run by a build, test runner,
+# package manager or shell on its own.
+_DOCUMENT_SUFFIXES = frozenset({
+ ".md", ".markdown", ".txt", ".rst", ".csv", ".tsv", ".log",
+ ".html", ".htm", ".svg", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".pdf",
+})
+# Structured data is inert unless a tool reads it to decide what to run. Those files are
+# dotfiles (`.eslintrc.json`, `.gitpod.yml`) or have well-known names, listed below.
+_DATA_SUFFIXES = frozenset({".json", ".jsonl", ".yaml", ".yml", ".xml"})
+_TOOL_CONFIG_NAMES = frozenset({
+ # package managers and task runners: scripts, tasks, hooks
+ "package.json", "package-lock.json", "composer.json", "deno.json", "deno.jsonc",
+ "turbo.json", "nx.json", "lerna.json", "taskfile.yml", "taskfile.yaml",
+ # build and transpile configs that load plugins
+ "babel.config.json", "tsconfig.json", "jsconfig.json", "angular.json", "project.json",
+ # containers and deploy targets
+ "docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml",
+ "vercel.json", "now.json", "firebase.json", "app.json", "app.yaml", "serverless.yml",
+ "serverless.yaml", "cloudbuild.yaml", "cloudbuild.yml", "fly.toml",
+ # CI systems not covered by the protected list
+ "azure-pipelines.yml", "bitbucket-pipelines.yml", "appveyor.yml", "codemagic.yaml",
+ "mkdocs.yml", "renovate.json",
+})
+
+_SENSITIVE_NAME = re.compile(
+ r"^\.env(\..*)?$"
+ r"|\.(pem|key|p12|pfx|kdbx|keystore|jks|ppk|gpg|asc)$"
+ r"|^id_(rsa|dsa|ecdsa|ed25519)"
+ r"|(^|[._-])(secret|secrets|credential|credentials|password|passwd|token|tokens"
+ r"|apikey|api[_-]key|private[_-]key)([._-]|$)"
+ r"|^\.(netrc|npmrc|pypirc|pgpass)$",
+ re.IGNORECASE,
+)
+_SECRET_VALUE = re.compile(
+ r"-----BEGIN [A-Z ]*PRIVATE KEY-----"
+ r"|\bsk-[A-Za-z0-9_-]{20,}"
+ r"|\b(AKIA|ASIA)[A-Z0-9]{16}\b"
+ r"|\bgh[pousr]_[A-Za-z0-9]{30,}"
+ r"|\bgithub_pat_[A-Za-z0-9_]{20,}"
+ r"|\bxox[abprs]-[A-Za-z0-9-]{10,}"
+ r"|\b(api[_-]?key|secret|token|password|passwd|access[_-]?key)\b[\"']?\s*[:=]\s*[\"']?[A-Za-z0-9_\-/+=]{16,}",
+ re.IGNORECASE,
+)
+
+# Git states this module reports for an existing file.
+TRACKED_CLEAN = "tracked_clean"
+TRACKED_MODIFIED = "tracked_modified"
+UNTRACKED = "untracked"
+IGNORED = "ignored"
+UNKNOWN = "unknown"
+
+
+def is_inert_name(name: str) -> bool:
+ lowered = name.lower()
+ suffix = os.path.splitext(lowered)[1]
+ if suffix in _DOCUMENT_SUFFIXES:
+ return True
+ if suffix in _DATA_SUFFIXES:
+ return not lowered.startswith(".") and lowered not in _TOOL_CONFIG_NAMES
+ return False
+
+
+def is_sensitive_name(name: str) -> bool:
+ return bool(_SENSITIVE_NAME.search(name))
+
+
+def _strings(value: Any, depth: int = 0) -> list[str]:
+ """Every string inside the arguments, raw (not JSON-escaped, so quotes and newlines
+ look the way they will on disk)."""
+ if depth > 6:
+ return []
+ if isinstance(value, str):
+ return [value]
+ if isinstance(value, dict):
+ return [s for v in value.values() for s in _strings(v, depth + 1)]
+ if isinstance(value, (list, tuple)):
+ return [s for v in value for s in _strings(v, depth + 1)]
+ return []
+
+
+def has_secret_value(arguments: dict[str, Any]) -> bool:
+ return any(_SECRET_VALUE.search(text) for text in _strings(arguments))
+
+
+def _git(args: list[str], cwd: Path) -> Optional[subprocess.CompletedProcess]:
+ exe = shutil.which("git")
+ if exe is None:
+ return None
+ env = {**os.environ, "GIT_OPTIONAL_LOCKS": "0"} # never take the index lock to look
+ try:
+ return subprocess.run(
+ [exe, *args], cwd=str(cwd), capture_output=True, timeout=5, env=env, check=False
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+
+
+def git_file_state(path: Path) -> str:
+ """State of an EXISTING file: tracked_clean, tracked_modified, untracked, ignored, or
+ unknown (no git, not a repository, or git failed)."""
+ folder = path.parent
+ top = _git(["rev-parse", "--show-toplevel"], folder)
+ if top is None or top.returncode != 0:
+ return UNKNOWN
+ root = Path(top.stdout.decode("utf-8", "replace").strip())
+ try:
+ rel = path.resolve().relative_to(root.resolve()).as_posix()
+ except ValueError:
+ return UNKNOWN
+ tracked = _git(["ls-files", "--error-unmatch", "--", rel], root)
+ if tracked is None:
+ return UNKNOWN
+ status = _git(["status", "--porcelain=v1", "--untracked-files=all", "--ignored", "--", rel], root)
+ if status is None or status.returncode != 0:
+ return UNKNOWN
+ lines = [ln for ln in status.stdout.decode("utf-8", "replace").splitlines() if ln.strip()]
+ if tracked.returncode == 0:
+ return TRACKED_CLEAN if not lines else TRACKED_MODIFIED
+ if any(ln.startswith("!!") for ln in lines):
+ return IGNORED
+ return UNTRACKED
+
+
+def inert_write_check(
+ arguments: dict[str, Any],
+ targets: list[Path],
+ *,
+ agent_wrote: Optional[Callable[[Path], bool]] = None,
+) -> tuple[bool, str]:
+ """(eligible, detail) for a write whose targets already passed the gate's floors (in a
+ writable root, not protected). `detail` says what made it eligible, for the audit row."""
+ if not targets:
+ return False, ""
+ if has_secret_value(arguments):
+ return False, ""
+ parts: list[str] = []
+ for target in targets:
+ name = target.name
+ if not is_inert_name(name) or is_sensitive_name(name):
+ return False, ""
+ if not target.exists():
+ parts.append(f"new file {name}")
+ elif agent_wrote is not None and agent_wrote(target):
+ parts.append(f"{name} written by the agent this session")
+ elif git_file_state(target) == TRACKED_CLEAN:
+ parts.append(f"{name} unchanged in git")
+ else:
+ return False, ""
+ return True, "; ".join(parts)
diff --git a/surfaces/gui/src/components/Transcript.test.tsx b/surfaces/gui/src/components/Transcript.test.tsx
index 204307e0..8c73cc69 100644
--- a/surfaces/gui/src/components/Transcript.test.tsx
+++ b/surfaces/gui/src/components/Transcript.test.tsx
@@ -127,6 +127,14 @@ describe("origin chips — standing MCP trust names its source", () => {
expect(chip.text).toBe("allowed for this request");
expect(chip.title).toContain("Allow for this request");
expect(chip.title).toContain("expired when the answer finished");
+
+ // OPE-233: an inert, reversible write the gate let through without the reviewer —
+ // the chip says what kind of change it was and that it can be undone.
+ cleanup();
+ const tier = chipFor("gate_tier");
+ expect(tier.text).toBe("safe change, no card");
+ expect(tier.title).toContain("without the reviewer");
+ expect(tier.title).toContain("can be undone");
});
});
diff --git a/surfaces/gui/src/components/Transcript.tsx b/surfaces/gui/src/components/Transcript.tsx
index b1b5a1ac..43758da2 100644
--- a/surfaces/gui/src/components/Transcript.tsx
+++ b/surfaces/gui/src/components/Transcript.tsx
@@ -191,6 +191,7 @@ function originChip(origin: string | undefined, note: string | undefined, grant?
origin !== "reviewer" &&
origin !== "bypass" &&
origin !== "run_grant" &&
+ origin !== "gate_tier" &&
!TRUST_ORIGINS.has(origin ?? "")
)
return null;
@@ -209,7 +210,9 @@ function originChip(origin: string | undefined, note: string | undefined, grant?
? t("transcript.approval.trusted_generic_title")
: origin === "run_grant"
? t("transcript.approval.run_grant_title")
- : t("transcript.approval.bypass_title")
+ : origin === "gate_tier"
+ ? t("transcript.approval.gate_tier_title")
+ : t("transcript.approval.bypass_title")
}
>
{origin === "reviewer"
@@ -222,7 +225,9 @@ function originChip(origin: string | undefined, note: string | undefined, grant?
? t("transcript.approval.trusted_generic")
: origin === "run_grant"
? t("transcript.approval.run_grant")
- : t("transcript.approval.bypassed")}
+ : origin === "gate_tier"
+ ? t("transcript.approval.gate_tier")
+ : t("transcript.approval.bypassed")}
</span>
);
}
diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.json
index 36bc1e01..b474a222 100644
--- a/surfaces/gui/src/locales/en.json
+++ b/surfaces/gui/src/locales/en.json
@@ -247,7 +247,9 @@
"trusted_generic": "allowed by standing trust",
"trusted_generic_title": "a standing trust setting (a per-tool rule, or the server's don't-ask flag) waived the card; mode gates, the reviewer, and the audit trail still applied",
"run_grant": "allowed for this request",
- "run_grant_title": "you chose 'Allow for this request' earlier in this answer — this call ran without a card. Its full arguments are in this transcript and the audit log; the grant expired when the answer finished"
+ "run_grant_title": "you chose 'Allow for this request' earlier in this answer — this call ran without a card. Its full arguments are in this transcript and the audit log; the grant expired when the answer finished",
+ "gate_tier": "safe change, no card",
+ "gate_tier_title": "Auto-approve let this run without the reviewer: an inert file (a document or data, not code) inside your folders that can be undone — a new file, a file unchanged in git, or one the agent wrote earlier. Its full arguments are in this transcript and the audit log"
},
"step": {
"raw": "raw",
diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.json
index 897a7ca0..5e2f1970 100644
--- a/surfaces/gui/src/locales/zh.json
+++ b/surfaces/gui/src/locales/zh.json
@@ -245,7 +245,9 @@
"trusted_generic": "按既有信任放行",
"trusted_generic_title": "某项既有信任设置(按工具的规则,或服务器的免询问标记)跳过了审批卡片;模式限制、审查器与审计记录仍然生效",
"run_grant": "本次请求内已允许",
- "run_grant_title": "您在本次回答早些时候选择了“本次请求内允许”——此调用未显示审批卡片。完整参数保存在会话记录与审计日志中;回答结束后该授权已失效"
+ "run_grant_title": "您在本次回答早些时候选择了“本次请求内允许”——此调用未显示审批卡片。完整参数保存在会话记录与审计日志中;回答结束后该授权已失效",
+ "gate_tier": "安全更改,无需审批卡片",
+ "gate_tier_title": "自动批准未经审查模型即运行了此操作:这是您文件夹内可撤销的非执行文件(文档或数据,而非代码)——新文件、在 git 中未修改的文件,或智能体早先写入的文件。完整参数保存在会话记录与审计日志中"
},
"step": {
"raw": "原始",
diff --git a/tests/test_config.py b/tests/test_config.py
index ac1da7e6..320f2d57 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -144,3 +144,15 @@ def test_cloud_endpoints_default_to_production():
cfg = Config()
assert cfg.cloud_base_url == "https://api.openworker.com"
assert cfg.cloud_relay_ws_url.startswith("wss://")
+
+
+def test_inert_writes_tier_is_user_global_only(tmp_path):
+ # OPE-233: a cloned repo must not be able to switch on a looser Auto-Approve gate.
+ g = tmp_path / "global.toml"
+ g.write_text('auto_approve_inert_writes = "audit"\n')
+ ws = tmp_path / "ws"
+ (ws / ".coworker").mkdir(parents=True)
+ (ws / ".coworker" / "config.toml").write_text('auto_approve_inert_writes = "on"\n')
+
+ assert load_config(ws, global_path=g).auto_approve_inert_writes == "audit"
+ assert load_config(ws, global_path=tmp_path / "none.toml").auto_approve_inert_writes == "off"
diff --git a/tests/test_inert_writes.py b/tests/test_inert_writes.py
new file mode 100644
index 00000000..256822d5
--- /dev/null
+++ b/tests/test_inert_writes.py
@@ -0,0 +1,297 @@
+"""Auto-approve's inert-writes tier (OPE-233).
+
+A write inside the session's folders runs without a reviewer call when it is an inert
+file type, its name and content don't look secret, it isn't a protected file, and it can
+be undone: a new file, a git-tracked file with no uncommitted changes, or a file the agent
+itself wrote earlier in the session. Every other write reaches the reviewer exactly as
+before. Behind `inert_writes`: "off" (default) → "audit" (decision unchanged, "would
+allow" recorded) → "on"."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from coworker.events import EventType
+from coworker.providers import AssistantTurn
+from coworker.permissions import INERT_WRITE_REASON, Mode, PermissionEngine
+from coworker.provenance import SessionFiles
+from test_auto_approve import _engine, _FakeReviewer, _run, _tool_turn
+
+git = pytest.mark.skipif(shutil.which("git") is None, reason="git not installed")
+
+
+def _gate(tmp_path: Path, inert: str = "on", mode: Mode = Mode.AUTO_APPROVE, **kw) -> PermissionEngine:
+ return PermissionEngine(workspace_root=tmp_path, mode=mode, inert_writes=inert, **kw)
+
+
+def _write(path: str, content: str = "hello", overwrite: bool = False) -> dict:
+ return {"path": path, "content": content, "overwrite": overwrite}
+
+
+def _repo(tmp_path: Path, files: dict[str, str]) -> None:
+ run = lambda *a: subprocess.run(["git", *a], cwd=tmp_path, check=True, capture_output=True) # noqa: E731
+ run("init", "-q")
+ for name, text in files.items():
+ (tmp_path / name).parent.mkdir(parents=True, exist_ok=True)
+ (tmp_path / name).write_text(text, encoding="utf-8")
+ run("add", "-A")
+ run("-c", "user.name=t", "-c", "[email protected]", "commit", "-qm", "init")
+
+
+def _ran_without_reviewer(d) -> bool:
+ return d.allowed and d.reason.startswith(INERT_WRITE_REASON) and d.tier == "inert_write"
+
+
+def _goes_to_reviewer(d) -> bool:
+ return not d.allowed and d.needs_user and not d.human_only
+
+
+# -- the flag ----------------------------------------------------------------------
+
+
+def test_off_by_default_every_write_still_reaches_the_reviewer(tmp_path):
+ d = PermissionEngine(workspace_root=tmp_path, mode=Mode.AUTO_APPROVE).evaluate(
+ "write_file", _write("notes.md")
+ )
+ assert _goes_to_reviewer(d) and d.tier == ""
+
+
+def test_on_a_new_inert_file_runs_without_the_reviewer(tmp_path):
+ assert _ran_without_reviewer(_gate(tmp_path).evaluate("write_file", _write("summary.txt")))
+
+
+def test_audit_mode_records_would_allow_but_changes_nothing(tmp_path):
+ d = _gate(tmp_path, "audit").evaluate("write_file", _write("summary.txt"))
+ assert _goes_to_reviewer(d)
+ assert d.reason == "requires approval"
+ assert d.tier == "inert_write" and d.tier_audit_only
+
+
[email protected]("mode", [Mode.INTERACTIVE, Mode.CUSTOM])
+def test_only_auto_approve_mode_uses_the_tier(tmp_path, mode):
+ d = _gate(tmp_path, mode=mode).evaluate("write_file", _write("summary.txt"))
+ assert not d.allowed and d.tier == ""
+
+
+def test_an_unknown_flag_value_means_off(tmp_path):
+ d = _gate(tmp_path, "yes please").evaluate("write_file", _write("summary.txt"))
+ assert _goes_to_reviewer(d)
+
+
+# -- what counts as inert --------------------------------------------------------------
+
+
+ "path",
+ ["notes.md", "out/report.txt", "data/rows.csv", "data/rows.tsv", "result.json", "cfg/settings.yaml",
+ "page.html", "chart.svg", "docs/guide.rst", "run.log", "NOTES.MD"],
+)
+def test_inert_types_are_eligible(tmp_path, path):
+ assert _ran_without_reviewer(_gate(tmp_path).evaluate("write_file", _write(path)))
+
+
+ "path",
+ ["make_report.py", "build.sh", "run.ps1", "app.js", "main.ts", "lib.rb", "x.c", "Makefile",
+ "Dockerfile", "fix.patch", "conftest.py", "sitecustomize.py", "x.pth", "noext"],
+)
+def test_code_scripts_and_unknown_types_go_to_the_reviewer(tmp_path, path):
+ assert _goes_to_reviewer(_gate(tmp_path).evaluate("write_file", _write(path)))
+
+
+ "path",
+ [".env", ".env.local", "secrets/.ENV.production", "server.pem", "api_key.txt", "API-KEY.json",
+ "credentials.json", "id_rsa.txt", "my_secrets.yaml", "token.txt", "password.txt"],
+)
+def test_secret_looking_names_go_to_the_reviewer(tmp_path, path):
+ assert _goes_to_reviewer(_gate(tmp_path).evaluate("write_file", _write(path)))
+
+
+ "content",
+ [
+ "key: sk-abcdefghijklmnopqrstuvwxyz012345",
+ "AKIAABCDEFGHIJKLMNOP",
+ "-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END OPENSSH PRIVATE KEY-----",
+ "token = ghp_abcdefghijklmnopqrstuvwxyz0123456789",
+ "slack: xoxb-1234567890-abcdefghij",
+ 'api_key = "Zx9Qw3Er7Ty1Ui5Op2As8Df4Gh6Jk0L"',
+ ],
+)
+def test_secret_looking_content_goes_to_the_reviewer(tmp_path, content):
+ assert _goes_to_reviewer(_gate(tmp_path).evaluate("write_file", _write("notes.md", content)))
+
+
+def test_ordinary_prose_about_keys_is_fine(tmp_path):
+ text = "Rotate the API key monthly. The password policy needs 12 characters."
+ assert _ran_without_reviewer(_gate(tmp_path).evaluate("write_file", _write("policy.md", text)))
+
+
+# -- floors still win -------------------------------------------------------------------
+
+
+def test_a_protected_inert_file_stays_human_only(tmp_path):
+ # AGENTS.md is markdown, but it is read into every later session's prompt (OPE-231).
+ d = _gate(tmp_path).evaluate("write_file", _write("AGENTS.md"))
+ assert not d.allowed and d.human_only and d.tier == ""
+
+
+def test_a_write_outside_the_folders_is_still_refused(tmp_path):
+ d = _gate(tmp_path / "ws").evaluate("write_file", _write("../outside.md"))
+ assert not d.allowed and not d.needs_user
+
+
+def test_a_read_only_root_is_still_refused(tmp_path):
+ ro = tmp_path / "ro"
+ ro.mkdir()
+ gate = PermissionEngine(
+ workspace_root=ro, mode=Mode.AUTO_APPROVE, inert_writes="on",
+ roots=[{"path": ro, "writable": False}],
+ )
+ d = gate.evaluate("write_file", _write("notes.md"))
+ assert not d.allowed and not d.needs_user
+
+
+# -- reversibility -----------------------------------------------------------------------
+
+
+def test_overwriting_an_existing_file_without_git_goes_to_the_reviewer(tmp_path):
+ (tmp_path / "notes.md").write_text("user's own notes", encoding="utf-8")
+ assert _goes_to_reviewer(_gate(tmp_path).evaluate("write_file", _write("notes.md", overwrite=True)))
+
+
+@git
+def test_a_new_file_in_a_repo_is_eligible(tmp_path):
+ _repo(tmp_path, {"README.md": "x"})
+ assert _ran_without_reviewer(_gate(tmp_path).evaluate("write_file", _write("summary.txt")))
+
+
+@git
+def test_a_tracked_unmodified_file_is_eligible(tmp_path):
+ _repo(tmp_path, {"docs/notes.md": "v1"})
+ d = _gate(tmp_path).evaluate("replace_in_file", {"path": "docs/notes.md", "old": "v1", "new": "v2"})
+ assert _ran_without_reviewer(d)
+
+
+@git
+def test_a_tracked_file_with_uncommitted_changes_goes_to_the_reviewer(tmp_path):
+ _repo(tmp_path, {"notes.md": "v1"})
+ (tmp_path / "notes.md").write_text("the user's unsaved edit", encoding="utf-8")
+ d = _gate(tmp_path).evaluate("write_file", _write("notes.md", overwrite=True))
+ assert _goes_to_reviewer(d)
+
+
+@git
+def test_an_untracked_existing_file_goes_to_the_reviewer(tmp_path):
+ _repo(tmp_path, {"README.md": "x"})
+ (tmp_path / "scratch.md").write_text("not in git", encoding="utf-8")
+ assert _goes_to_reviewer(_gate(tmp_path).evaluate("write_file", _write("scratch.md", overwrite=True)))
+
+
+@git
+def test_an_ignored_existing_file_goes_to_the_reviewer(tmp_path):
+ _repo(tmp_path, {".gitignore": "out/\n"})
+ (tmp_path / "out").mkdir()
+ (tmp_path / "out" / "result.json").write_text("{}", encoding="utf-8")
+ d = _gate(tmp_path).evaluate("write_file", _write("out/result.json", overwrite=True))
+ assert _goes_to_reviewer(d)
+
+
+@git
+def test_deleting_a_tracked_unmodified_file_is_eligible(tmp_path):
+ _repo(tmp_path, {"old-notes.txt": "old"})
+ patch = "*** Begin Patch\n*** Delete File: old-notes.txt\n*** End Patch"
+ assert _ran_without_reviewer(_gate(tmp_path).evaluate("apply_patch", {"patch": patch}))
+
+
+@git
+def test_deleting_an_untracked_file_goes_to_the_reviewer(tmp_path):
+ _repo(tmp_path, {"README.md": "x"})
+ (tmp_path / "keep.txt").write_text("only copy", encoding="utf-8")
+ patch = "*** Begin Patch\n*** Delete File: keep.txt\n*** End Patch"
+ assert _goes_to_reviewer(_gate(tmp_path).evaluate("apply_patch", {"patch": patch}))
+
+
+def test_a_patch_touching_one_inert_and_one_code_file_goes_to_the_reviewer(tmp_path):
+ patch = (
+ "*** Begin Patch\n*** Add File: notes.md\n+hi\n"
+ "*** Add File: tool.py\n+print(1)\n*** End Patch"
+ )
+ assert _goes_to_reviewer(_gate(tmp_path).evaluate("apply_patch", {"patch": patch}))
+
+
+def test_rewriting_a_file_the_agent_wrote_this_session_is_eligible(tmp_path):
+ files = SessionFiles(tmp_path)
+ gate = _gate(tmp_path, agent_wrote=files.wrote)
+ assert _ran_without_reviewer(gate.evaluate("write_file", _write("summary.txt")))
+ # The write ran: the file exists now and the engine recorded it.
+ (tmp_path / "summary.txt").write_text("hello", encoding="utf-8")
+ files.record("write_file", _write("summary.txt"), "ok", step=1)
+ assert _ran_without_reviewer(gate.evaluate("write_file", _write("summary.txt", "v2", overwrite=True)))
+
+
+def test_a_file_the_agent_only_downloaded_is_not_treated_as_its_own(tmp_path):
+ files = SessionFiles(tmp_path)
+ (tmp_path / "page.html").write_text("<html>", encoding="utf-8")
+ files.record("email_download_attachment", {"id": "m1"}, {"path": str(tmp_path / "page.html")}, step=1)
+ assert files.match("run_shell", {"command": "bash ./page.html"}, step=2) is not None # recorded, as a download
+ gate = _gate(tmp_path, agent_wrote=files.wrote)
+ assert _goes_to_reviewer(gate.evaluate("write_file", _write("page.html", overwrite=True)))
+
+
+# -- the engine: recorded, never invisible ------------------------------------------------
+
+
+def _todo_engine(tmp_path, inert: str):
+ engine, rows, approvals = _engine(
+ tmp_path,
+ [
+ _tool_turn(("write_file", {"path": "summary.txt", "content": "Weekly summary: 3 tasks done."})),
+ _tool_turn(("write_file", {"path": "summary.txt", "content": "Weekly summary: 4 tasks done."})),
+ _tool_turn(("write_file", {"path": "tool.py", "content": "print(1)"})),
+ AssistantTurn(text="done", finish_reason="stop"),
+ ],
+ )
+ engine.permissions.inert_writes = inert
+ engine.reviewer = _FakeReviewer({"write_file": "unsure"}) # it can't see the to-do list
+ return engine, rows, approvals
+
+
+def test_engine_runs_inert_writes_without_the_reviewer_and_records_them(tmp_path):
+ engine, rows, approvals = _todo_engine(tmp_path, "on")
+ events = _run(engine, "do the tasks in TODO.md")
+
+ asked = [args.get("path") for name, args in engine.reviewer.asked]
+ assert asked == ["tool.py"] # only the code file reached the reviewer
+ assert approvals == ["write_file"] # ...whose "unsure" became the one card
+ tier_rows = [r for r in rows if r.get("stage") == "auto_allowed" and INERT_WRITE_REASON in (r.get("reason") or "")]
+ assert len(tier_rows) == 2
+ origins = [ev.data.get("approval_origin") for ev in events if ev.type == EventType.TOOL_FINISHED]
+ assert origins.count("gate_tier") == 2
+
+
+def test_engine_audit_mode_changes_nothing_but_records_would_allow(tmp_path):
+ engine, rows, approvals = _todo_engine(tmp_path, "audit")
+ _run(engine, "do the tasks in TODO.md")
+
+ assert len(engine.reviewer.asked) == 3 # unchanged: every write reached the reviewer
+ shadow = [r for r in rows if r.get("stage") == "gate_tier_shadow"]
+ # Both summary.txt writes would have been allowed; tool.py would not.
+ assert [r.get("status") for r in shadow] == ["would_allow", "would_allow"]
+ assert all("summary.txt" in r["reason"] for r in shadow)
+
+
+def test_an_existing_file_the_agent_did_not_write_still_reaches_the_reviewer(tmp_path):
+ engine, rows, approvals = _todo_engine(tmp_path, "on")
+ (tmp_path / "summary.txt").write_text("the user's file", encoding="utf-8") # no git
+ _run(engine, "do the tasks in TODO.md")
+
+ # First write: an existing file nobody can restore → reviewer → card. After the user
+ # approves it, the file holds the agent's bytes, so the second write is eligible.
+ asked = [args.get("path") for name, args in engine.reviewer.asked]
+ assert asked == ["summary.txt", "tool.py"]