Skip to content
Python

fix(auto-approve): spreadsheet formulas and workspace folder names in the safe-write tier (OPE-233)

Devika Verma0243bbf9a686
diff --git a/coworker/permissions.py b/coworker/permissions.py
index a5f28639..5aa20e4c 100644
--- a/coworker/permissions.py
+++ b/coworker/permissions.py
@@ -972,7 +972,8 @@ class PermissionEngine:
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
+ arguments, [self._candidate(p) for p in paths], agent_wrote=self.agent_wrote,
+ roots=[rp for rp, writable in self._resolved_roots() if writable],
)
if eligible and self.inert_writes == "on":
return Decision(True, f"{INERT_WRITE_REASON}: {detail}", tier="inert_write")
diff --git a/coworker/workspace_safety.py b/coworker/workspace_safety.py
index f34a2e0b..e6341a0c 100644
--- a/coworker/workspace_safety.py
+++ b/coworker/workspace_safety.py
@@ -5,12 +5,22 @@ can execute later: a plain document or raster image that no build, installer, te
or other AI tool reads as instructions, 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. JSON and YAML are never eligible: tools read them to decide what
-to run, and no list of their names can be complete, so the reviewer sees that content. Every check fails toward "ask the reviewer": an unknown file type,
-an unreadable git state or a doubtful name keeps today's behaviour.
+to run, and no list of their names can be complete, so the reviewer sees that content.
+
+The line between a document and an excluded file: a file leaves the tier when its purpose
+is to tell a tool what to do (requirements.txt, CMakeLists.txt, CLAUDE.md), when a tool
+runs it with no opt-in (test*.txt under default pytest), or when merely opening it can act
+(a spreadsheet cell that starts a formula). A file whose purpose is prose stays, even if a
+project can opt in to running it (a README under `cargo test`, a MyST notebook under
+`jupyter-book build`): the command that would run it still reaches the reviewer.
+
+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 csv
import os
import re
import shutil
@@ -31,11 +41,16 @@ _DOCUMENT_SUFFIXES = frozenset({
})
# Text files that decide what gets built, installed or tested: CMake runs CMakeLists.txt,
# pip installs what requirements and constraints files list (`requirements-dev.txt`,
-# `dev-requirements.txt`, `requirements/base.txt`), and pytest runs `test*.txt` as doctests
-# by default.
+# `dev-requirements.txt`, `requirements/base.txt`), platforms install what runtime.txt
+# (Heroku), packages.txt (Streamlit Cloud) and apt.txt (Binder) name, and pytest runs
+# `test*.txt` as doctests by default.
_BUILD_INPUT_NAME = re.compile(
- r"^cmakelists\.txt$|^test.*\.txt$|(requirements|constraints).*\.txt$", re.IGNORECASE
+ r"^(cmakelists|runtime|packages|apt)\.txt$|^test.*\.txt$"
+ r"|(requirements|constraints).*\.txt$",
+ re.IGNORECASE,
)
+# Only `.txt` files under these folders: pip reads `requirements/base.txt`, not a Markdown
+# file kept there.
_BUILD_INPUT_FOLDERS = frozenset({"requirements"})
# Instructions other AI coding tools read into their prompt on their next run, so a write
# here steers a later agent. AGENTS.md is not listed: the protected list (permissions.py)
@@ -47,16 +62,23 @@ _AGENT_INSTRUCTION_NAME = re.compile(
re.IGNORECASE,
)
# Every file in these folders, at any depth: Claude Code, Cursor, Windsurf, Cline, Roo,
-# Kiro, Amazon Q, Continue, Junie, Augment, Gemini, Antigravity, OpenHands, Trae, Codex
-# and OpenCode keep rules, commands, prompts and skills there.
+# Kilo Code, Kiro, Amazon Q, Continue, Junie, JetBrains AI Assistant, Augment, Gemini,
+# Antigravity, OpenHands, Trae, Codex, OpenCode and Zencoder keep rules, commands,
+# prompts and skills there.
_AGENT_FOLDERS = frozenset({
- ".claude", ".cursor", ".windsurf", ".clinerules", ".roo", ".kiro", ".amazonq",
- ".continue", ".junie", ".augment", ".gemini", ".agent", ".agents", ".openhands",
- ".trae", ".codex", ".opencode",
+ ".claude", ".cursor", ".windsurf", ".clinerules", ".roo", ".kilocode", ".kiro",
+ ".amazonq", ".continue", ".junie", ".aiassistant", ".augment", ".gemini", ".agent",
+ ".agents", ".openhands", ".trae", ".codex", ".opencode", ".zencoder",
})
# Under .github/, only Copilot's folders: CONTRIBUTING.md and issue templates stay eligible.
_GITHUB_AGENT_FOLDERS = frozenset({"instructions", "prompts", "chatmodes", "agents", "skills"})
+# Spreadsheet apps evaluate a cell that starts with = @ + or - when a .csv/.tsv is opened,
+# and opening a file is not a command anyone reviews. A signed cell is a number only when
+# all of it is one (-5, +1.5, -.5, -2e3): `-2+3+cmd|...` is a formula.
+_SPREADSHEET_DELIMITERS = {".csv": ",", ".tsv": "\t"}
+_NUMBER_CELL = re.compile(r"[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?%?")
+
_SENSITIVE_NAME = re.compile(
r"^\.env(\..*)?$"
r"|\.(pem|key|p12|pfx|kdbx|keystore|jks|ppk|gpg|asc)$"
@@ -91,14 +113,25 @@ def is_inert_name(name: str) -> bool:
return not (_BUILD_INPUT_NAME.search(name) or _AGENT_INSTRUCTION_NAME.search(name))
-def is_inert_path(path: Path) -> bool:
+def is_inert_path(path: Path, root: Optional[Path] = None) -> bool:
"""`is_inert_name`, and not inside a folder that build tools or AI tools read from.
- Folder names match in any letter case and anywhere in the path: a doubtful match only
- sends the write to the reviewer."""
+ Folder names match in any letter case, at any depth under `root` (a writable root the
+ path is in); the root's own name and everything above it are the user's choice and
+ are not matched, so a workspace called `requirements` keeps the tier for its notes.
+ Without a root every folder counts, and a doubtful match only sends the write to the
+ reviewer."""
if not is_inert_name(path.name):
return False
- folders = [part.casefold() for part in path.parts[:-1]]
- if any(f in _AGENT_FOLDERS or f in _BUILD_INPUT_FOLDERS for f in folders):
+ inside = path
+ if root is not None:
+ try:
+ inside = path.relative_to(root)
+ except ValueError:
+ pass
+ folders = [part.casefold() for part in inside.parts[:-1]]
+ if any(f in _AGENT_FOLDERS for f in folders):
+ return False
+ if path.suffix.lower() == ".txt" and any(f in _BUILD_INPUT_FOLDERS for f in folders):
return False
return not any(
parent == ".github" and child in _GITHUB_AGENT_FOLDERS
@@ -106,6 +139,16 @@ def is_inert_path(path: Path) -> bool:
)
+def _root_of(path: Path, roots: Optional[list[Path]]) -> Optional[Path]:
+ for root in roots or []:
+ try:
+ path.relative_to(root)
+ return root
+ except ValueError:
+ continue
+ return None
+
+
def is_sensitive_name(name: str) -> bool:
return bool(_SENSITIVE_NAME.search(name))
@@ -128,6 +171,46 @@ def has_secret_value(arguments: dict[str, Any]) -> bool:
return any(_SECRET_VALUE.search(text) for text in _strings(arguments))
+def _written_lines(arguments: dict[str, Any]) -> list[str]:
+ """The lines a write puts on disk: whole string arguments, or for a patch or diff only
+ its added lines, without the leading `+`."""
+ out: list[str] = []
+ for key, value in (arguments or {}).items():
+ if key in ("patch", "diff") and isinstance(value, str):
+ out.extend(
+ ln[1:] for ln in value.splitlines() if ln.startswith("+") and not ln.startswith("+++")
+ )
+ else:
+ out.extend(ln for text in _strings(value) for ln in text.splitlines())
+ return out
+
+
+def _starts_formula(field: str) -> bool:
+ cell = field.strip().strip("\"'").strip() # apps drop the quotes before evaluating
+ if not cell:
+ return False
+ if cell[0] in "=@":
+ return True
+ if cell[0] in "+-":
+ return cell != "-" and not _NUMBER_CELL.fullmatch(cell) # a lone dash marks "none"
+ return False
+
+
+def has_formula_cell(arguments: dict[str, Any], delimiter: str = ",") -> bool:
+ """True when any cell in the written text starts a spreadsheet formula. Lines are split
+ on `delimiter` with quoting as a spreadsheet app reads it, so a comma inside a quoted
+ cell doesn't start a new one. Call it only for .csv/.tsv targets; a line the csv
+ module can't parse counts as a formula (reviewer)."""
+ for line in _written_lines(arguments):
+ try:
+ fields = next(csv.reader([line], delimiter=delimiter), [])
+ except csv.Error:
+ return True
+ if any(_starts_formula(f) for f in fields):
+ return True
+ return False
+
+
def _git(args: list[str], cwd: Path) -> Optional[subprocess.CompletedProcess]:
exe = shutil.which("git")
if exe is None:
@@ -183,19 +266,24 @@ def inert_write_check(
targets: list[Path],
*,
agent_wrote: Optional[Callable[[Path], bool]] = None,
+ roots: Optional[list[Path]] = 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."""
+ writable root, not protected). `roots` are the resolved writable roots, so folder rules
+ look only below them. `detail` says what made it eligible, for the audit row."""
if not targets:
return False, ""
if has_secret_value(arguments):
return False, ""
if removes_files(arguments):
return False, ""
+ for delimiter in {_SPREADSHEET_DELIMITERS.get(t.suffix.lower()) for t in targets} - {None}:
+ if has_formula_cell(arguments, delimiter):
+ return False, ""
parts: list[str] = []
for target in targets:
name = target.name
- if not is_inert_path(target) or is_sensitive_name(name):
+ if not is_inert_path(target, _root_of(target, roots)) or is_sensitive_name(name):
return False, ""
if not target.exists():
parts.append(f"new file {name}")
diff --git a/tests/test_inert_writes.py b/tests/test_inert_writes.py
index 361a42a5..811836fe 100644
--- a/tests/test_inert_writes.py
+++ b/tests/test_inert_writes.py
@@ -117,8 +117,10 @@ def test_json_and_yaml_go_to_the_reviewer(tmp_path, path):
# pytest runs test*.txt files as doctests by default.
["CMakeLists.txt", "src/lib/cmakelists.TXT", "requirements.txt", "REQUIREMENTS.txt",
"requirements-dev.txt", "requirements_test.txt", "dev-requirements.txt",
- "requirements/base.txt", "constraints.txt", "ci/constraints-py311.txt",
- "test_examples.txt", "docs/testing.txt"],
+ "requirements/base.txt", "requirements/dev/extra.txt", "constraints.txt",
+ "ci/constraints-py311.txt", "test_examples.txt", "docs/testing.txt",
+ # files that pick what a platform installs: Heroku, Streamlit Cloud, Binder
+ "runtime.txt", "packages.txt", "apt.txt"],
)
def test_build_and_install_inputs_go_to_the_reviewer(tmp_path, path):
assert _goes_to_reviewer(_gate(tmp_path).evaluate("write_file", _write(path)))
@@ -138,12 +140,92 @@ def test_build_and_install_inputs_go_to_the_reviewer(tmp_path, path):
".amazonq/rules/style.md", ".continue/rules/style.md", ".junie/guidelines.md",
".augment/rules/style.md", ".gemini/styleguide.md", ".agent/rules/style.md",
".agents/rules/style.md", ".openhands/microagents/repo.md", ".trae/rules/project_rules.md",
- ".codex/notes.md", ".opencode/agent/review.md"],
+ ".codex/notes.md", ".opencode/agent/review.md", ".kilocode/rules/style.md",
+ ".aiassistant/rules/style.md", ".zencoder/rules/style.md"],
)
def test_other_ai_tools_instruction_files_go_to_the_reviewer(tmp_path, path):
assert _goes_to_reviewer(_gate(tmp_path).evaluate("write_file", _write(path)))
[email protected]("folder", ["requirements", "agents", "Requirements Review"])
+def test_the_workspace_folder_name_itself_is_not_matched(tmp_path, folder):
+ # Folder rules look only at the path under the writable root: a workspace that is
+ # itself called `requirements` keeps the tier for its notes.
+ ws = tmp_path / folder
+ ws.mkdir()
+ assert _ran_without_reviewer(_gate(ws).evaluate("write_file", _write("notes.md")))
+ assert _ran_without_reviewer(_gate(ws).evaluate("write_file", _write("notes.txt")))
+
+
+def test_a_document_in_a_requirements_folder_is_still_eligible(tmp_path):
+ # pip reads `requirements/*.txt`; it does not read a Markdown file kept there.
+ assert _ran_without_reviewer(_gate(tmp_path).evaluate("write_file", _write("requirements/notes.md")))
+
+
+def test_a_second_writable_root_is_scoped_the_same_way(tmp_path):
+ extra = tmp_path / "requirements"
+ extra.mkdir()
+ gate = PermissionEngine(
+ workspace_root=tmp_path, mode=Mode.AUTO_APPROVE, inert_writes="on",
+ roots=[{"path": tmp_path, "writable": True}, {"path": extra, "writable": True}],
+ )
+ assert _ran_without_reviewer(gate.evaluate("write_file", _write(str(extra / "notes.md"))))
+ assert _goes_to_reviewer(gate.evaluate("write_file", _write("requirements/base.txt")))
+
+
+# -- spreadsheet formulas ------------------------------------------------------------------
+
+
+ "content",
+ [
+ 'name,total\nbob,=HYPERLINK("http://x","click")\n',
+ "name,total\nbob,\"=cmd|'/c calc'!A0\"\n",
+ "a,b\n@SUM(1;2),1\n",
+ "a,b\n+cmd|' /C calc'!A0,1\n",
+ "a,b\n-2+3+cmd|' /C calc'!A0,1\n",
+ "a\tb\n=1+1\t2\n",
+ "a,b\n 'x',=1+1\n", # leading space and quote do not hide the formula
+ ],
+)
+def test_a_csv_cell_that_starts_a_formula_goes_to_the_reviewer(tmp_path, content):
+ # A spreadsheet app runs a cell that starts with = @ + or - when the file is opened.
+ # Opening a file is not a command anyone reviews, so the reviewer must see it first.
+ name = "rows.tsv" if "\t" in content else "rows.csv"
+ assert _goes_to_reviewer(_gate(tmp_path).evaluate("write_file", _write(name, content)))
+
+
+ "content",
+ ["name,total\nbob,-5\nann,+1.5\n", "x,y\n-0.25,-.5\n", "a,b\n1,2\n",
+ 'note\n"well, =not at the start"\n', "a,b\n,\n"],
+)
+def test_ordinary_csv_data_is_still_eligible(tmp_path, content):
+ assert _ran_without_reviewer(_gate(tmp_path).evaluate("write_file", _write("rows.csv", content)))
+
+
+def test_a_formula_in_a_markdown_file_is_fine(tmp_path):
+ # Only spreadsheet files are opened by an app that evaluates cells.
+ text = "| a | b |\n|---|---|\n| =SUM(1,2) | x |\n"
+ assert _ran_without_reviewer(_gate(tmp_path).evaluate("write_file", _write("table.md", text)))
+
+
+def test_a_csv_patch_is_checked_on_its_added_lines(tmp_path):
+ bad = "*** Begin Patch\n*** Add File: rows.csv\n+a,b\n+=1+1,2\n*** End Patch"
+ assert _goes_to_reviewer(_gate(tmp_path).evaluate("apply_patch", {"patch": bad}))
+ ok = "*** Begin Patch\n*** Add File: rows.csv\n+a,b\n+1,2\n+-5,+2\n*** End Patch"
+ assert _ran_without_reviewer(_gate(tmp_path).evaluate("apply_patch", {"patch": ok}))
+
+
+def test_a_csv_replace_is_checked_on_the_new_text(tmp_path):
+ files = SessionFiles(tmp_path)
+ gate = _gate(tmp_path, agent_wrote=files.wrote)
+ (tmp_path / "rows.csv").write_text("a,b\n1,2\n", encoding="utf-8")
+ files.record("write_file", _write("rows.csv", "a,b\n1,2\n"), "ok", step=1)
+ args = {"path": "rows.csv", "old": "1,2", "new": "=1+1,2"}
+ assert _goes_to_reviewer(gate.evaluate("replace_in_file", args))
+
+
@pytest.mark.parametrize(
"path",
["make_report.py", "build.sh", "run.ps1", "app.js", "main.ts", "lib.rb", "x.c", "Makefile",