Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 55 additions & 10 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,22 +1,30 @@
# Reviewing outside PRs. See scripts/pr_sandbox/README.md.
#
# make pr-sandbox PR=612 # 1. triage risky files, run the PR's tests in the sandbox
# make pr-merge PR=612 # or, for a stale PR: merge BASE into it first
# make pr-review PR=612 # 2. start Claude on it: read-only, never prompts
# make pr-clean # 3. delete fetched PR refs and sandbox work dirs
# make pr-push PR=612 # 3. after pr-merge: push the merge to the PR (asks first)
# make pr-clean # 4. delete fetched PR refs and sandbox work dirs
#
# Options: BASE=master branch the PR targets (default: dev)
# TESTS="tests/test_x.py -x" pytest arguments (default: the whole suite)
# DEPS=merge-base take uv.lock/pyproject.toml from the PR's merge-base with BASE
# instead of this checkout (for stale PRs; default: checkout)
# OPTS="--fail-on medium" extra sandbox-pr.sh options (--python, --no-strace, --remote ...)
# CLAUDE_CMD=... default: the `claude` command from your interactive zsh
# pr-merge: AGENT=0 resolve conflicts in your editor instead of with Claude
# REDO=1 redo a merge you already accepted
# COMMIT=<sha> use a merge you made by hand

SHELL := /bin/bash
BASE ?= dev
DEPS ?= checkout
PR_TMP ?= /tmp
CLAUDE_CMD ?= claude
SANDBOX := scripts/pr_sandbox

.DEFAULT_GOAL := help
.PHONY: help pr-sandbox pr-review pr-clean _require-pr
.PHONY: help pr-sandbox pr-merge pr-review pr-push pr-clean _require-pr

help:
@echo "Reviewing an outside PR (run from your own dev checkout, in this order):"
Expand All @@ -25,26 +33,56 @@ help:
@echo " CI, agent config, pickles), then after you confirm, run its"
@echo " tests in the network-less sandbox and report anything"
@echo " suspicious. Exit status 2 = suspicious behaviour found."
@echo " 2. make pr-review PR=<N> Start Claude on the PR and its latest sandbox report. It can"
@echo " read and search freely without asking; everything else"
@echo " (running code, network, edits) is refused automatically."
@echo " 3. make pr-clean Delete the fetched PR refs and all sandbox work dirs."
@echo " make pr-merge PR=<N> Instead of pr-sandbox, for a stale PR (conflicts with BASE,"
@echo " or the contributor won't rebase): merges BASE into the PR in"
@echo " memory (nothing is checked out). A locked-down Claude agent"
@echo " resolves the conflicts (file tools only, confined to copies"
@echo " of the conflicted files); you see every resolution and accept"
@echo " it. Then it commits the merge and runs pr-sandbox's checks and"
@echo " tests on it, with the current dependencies."
@echo " 2. make pr-review PR=<N> Start Claude on the PR and its latest sandbox report (and the"
@echo " conflict resolution, after pr-merge). It can read and search"
@echo " freely without asking; everything else (running code,"
@echo " network, edits) is refused automatically."
@echo " 3. make pr-push PR=<N> After pr-merge: push the merge commit to the PR's branch (a"
@echo " fast-forward; asks first), so the PR can be merged. If"
@echo " maintainers can't push there, offers to open a new PR."
@echo " 4. make pr-clean Delete the fetched PR refs, merges and all sandbox work dirs."
@echo
@echo "Options:"
@echo " BASE=master Branch the PR targets (default: dev)"
@echo " TESTS=\"tests/test_x.py -x\" pytest arguments for pr-sandbox (default: whole suite)"
@echo " DEPS=merge-base Install dependencies from the PR's merge-base with BASE instead"
@echo " of this checkout. For stale PRs that still need a dependency"
@echo " the current branch dropped (default: checkout)"
@echo " OPTS=\"--fail-on medium\" Extra sandbox-pr.sh options (--python, --no-strace, --remote)"
@echo " CLAUDE_CMD=... Command pr-review launches (default: claude from your zsh)"
@echo " CLAUDE_CMD=... Command pr-review and pr-merge launch (default: claude from"
@echo " your zsh)"
@echo
@echo "Options for pr-merge (plus BASE, TESTS, CLAUDE_CMD and OPTS=\"--python ... --fail-on ...\"):"
@echo " AGENT=0 Resolve conflicts in your editor instead of with Claude"
@echo " REDO=1 Redo a merge you already accepted"
@echo " COMMIT=<sha> Test and keep a merge you made by hand (pr-merge explains"
@echo " how, for conflicts it can't handle)"
@echo
@echo "Details: scripts/pr_sandbox/README.md"

_require-pr:
@[[ "$(PR)" =~ ^[0-9]+$$ ]] || { echo "usage: make $(firstword $(MAKECMDGOALS)) PR=<number>" >&2; exit 1; }

pr-sandbox: _require-pr
$(SANDBOX)/sandbox-pr.sh --base "$(BASE)" \
$(SANDBOX)/sandbox-pr.sh --base "$(BASE)" --deps-from "$(DEPS)" \
--out "$(PR_TMP)/deepdiff-pr-$(PR)-$$(date +%Y%m%d-%H%M%S)" $(OPTS) $(PR) $(if $(TESTS),-- $(TESTS))

pr-merge: _require-pr
$(SANDBOX)/merge-pr.py merge --base "$(BASE)" --tmp "$(PR_TMP)" --claude-cmd '$(CLAUDE_CMD)' \
$(if $(filter 0 no,$(AGENT)),--no-agent) $(if $(filter 1 yes,$(REDO)),--redo) \
$(if $(COMMIT),--use-commit "$(COMMIT)") \
--out "$(PR_TMP)/deepdiff-pr-$(PR)-$$(date +%Y%m%d-%H%M%S)" $(OPTS) $(PR) $(if $(TESTS),-- $(TESTS))

pr-push: _require-pr
$(SANDBOX)/merge-pr.py push $(PR)

# Runs your `claude` from an interactive zsh so the zshrc wrapper (which switches to
# ai_agent) is used. --permission-mode dontAsk beats the user-level "auto" default: reads in
# the repo and the sandbox work dir (--add-dir), read-only commands and `gh pr view/diff`
Expand All @@ -59,8 +97,15 @@ pr-review: _require-pr
fi; \
echo "==> reviewing PR $(PR) with report $$report"; \
prompt=$$(sed -e "s|{PR}|$(PR)|g" -e "s|{REPORT}|$$report|g" $(SANDBOX)/review-prompt.md); \
zsh -ic '$(CLAUDE_CMD) --permission-mode dontAsk --settings "$$1" --add-dir "$$2" -- "$$3"' _ \
"$(CURDIR)/$(SANDBOX)/review-settings.json" "$$(dirname "$$report")" "$$prompt"
merge=$$(dirname "$$report"); \
if grep -qs '^merge ' "$$report/source.txt"; then \
merge=$$(ls -dt "$(PR_TMP)"/deepdiff-pr-$(PR)-merge-* 2>/dev/null | head -1); \
echo "==> the report is for a merge with $(BASE); including its conflict resolution from $$merge"; \
prompt+=$$'\n\n'$$(sed -e "s|{PR}|$(PR)|g" -e "s|{BASE}|$(BASE)|g" -e "s|{MERGE}|$$merge|g" \
$(SANDBOX)/review-prompt-merge.md); \
fi; \
zsh -ic '$(CLAUDE_CMD) --permission-mode dontAsk --settings "$$1" --add-dir "$$2" --add-dir "$$3" -- "$$4"' _ \
"$(CURDIR)/$(SANDBOX)/review-settings.json" "$$(dirname "$$report")" "$$merge" "$$prompt"

pr-clean:
git for-each-ref --format='%(refname)' refs/pr-sandbox | xargs -r -n1 git update-ref -d
Expand Down
74 changes: 73 additions & 1 deletion scripts/pr_sandbox/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@ make pr-review PR=612 # start Claude on the PR and its sandbox report, aut
make pr-clean # delete fetched PR refs and sandbox work dirs
```

For a stale PR (one that conflicts with `dev`, or whose contributor won't rebase), use
`make pr-merge` instead of `make pr-sandbox`. It merges `dev` into the PR and tests the merge.
See [Stale PRs: `make pr-merge`](#stale-prs-make-pr-merge):

```bash
make pr-merge PR=618 # merge dev into the PR, AI-resolve conflicts, you review, then sandbox
make pr-review PR=618 # same review, plus the conflict resolution
make pr-push PR=618 # push the merge to the PR's branch (asks first)
```

`make pr-review` runs your `claude` command from an interactive zsh, so a zshrc wrapper
(e.g. one that switches user) is used. It needs that wrapper to pass its arguments through
and keep the current directory. It starts Claude in `dontAsk` mode with
Expand All @@ -31,7 +41,8 @@ and keep the current directory. It starts Claude in `dontAsk` mode with

The initial prompt comes from `review-prompt.md`. Nothing is written to
`.claude/settings.local.json`, so your other sessions keep their mode. Options:
`BASE=master`, `TESTS="tests/test_x.py -x"`, `OPTS="--fail-on medium"`, `CLAUDE_CMD=...`.
`BASE=master`, `TESTS="tests/test_x.py -x"`, `DEPS=merge-base`, `OPTS="--fail-on medium"`,
`CLAUDE_CMD=...`.

The scripts can also be run directly:

Expand All @@ -40,6 +51,8 @@ The scripts can also be run directly:
scripts/pr_sandbox/sandbox-pr.sh 660 # review risky files, then run the tests
scripts/pr_sandbox/sandbox-pr.sh 660 -- tests/test_tsv.py -x
scripts/pr_sandbox/sandbox-pr.sh --base master 661 # PR targeting master
scripts/pr_sandbox/sandbox-pr.sh --deps-from merge-base 618 # stale PR: deps from its merge-base
scripts/pr_sandbox/merge-pr.py merge 618 # stale PR: merge dev into it, then sandbox
scripts/pr_sandbox/run-sandboxed.sh path/to/src # any directory with deepdiff/ + tests/
```

Expand All @@ -61,6 +74,10 @@ Reports are written to the `report/` dir that the output names: `report.md`, `fi
Dependencies are installed from *your* `uv.lock` (hash-checked), and the pytest config comes
from *your* `pyproject.toml`. The PR's build backend, `noxfile.py` and dependency changes
never run.

An old PR's `deepdiff/` can still import a dependency that your branch has since dropped
(e.g. `cachebox`), so its tests fail at import. Use `make pr-merge` (see below) to test it
merged with your branch.
4. **Sandbox** (`bwrap`):
- no network (an empty network namespace)
- its own PID/IPC/UTS namespaces and no controlling terminal (`--new-session` blocks
Expand Down Expand Up @@ -95,6 +112,61 @@ known helpers such as pytest-benchmark calling `git`/`hg` and `platform` calling
legitimate change trips a rule, add to the allowlists at the top of `analyze.py` with a comment
explaining why. Don't loosen the rules to make a PR pass.

## Stale PRs: `make pr-merge`

When a PR has gone stale (it conflicts with `dev`, or its code still needs a dependency `dev`
has dropped) and the contributor won't rebase it, bring it up to date yourself:

```bash
make pr-merge PR=618 # BASE=master for PRs to master
```

It goes through six numbered steps and says at each one what it's doing and what it needs
from you:

1. **Fetch** the PR and `dev` into `refs/pr-sandbox/` (no checkout).
2. **Merge `dev` into the PR in memory** with `git merge-tree`. Nothing is checked out, so none
of the PR's files (`.envrc`, `.claude/`, `CLAUDE.md`, hooks) land in a working tree. A merge
(rather than a rebase) keeps the contributor's commits as they are, so it can be pushed to
their branch as a fast-forward.
3. **Resolve conflicts with a locked-down Claude agent.** Only copies of the conflicted files
go into a scratch dir, renamed to `conflicts/NN.txt` (so a conflicted `CLAUDE.md` or
`.claude/settings.json` is never loaded as config), along with each side's diff and commit
subjects. The agent runs with `claude -p --restricted --tools Read,Edit,Write,Glob,Grep
--strict-mcp-config`: no shell, no web, no MCP connectors, user and project settings ignored.
A guard hook (`merge-guard.py`) confines its reads to the scratch dir and its writes to
`conflicts/*` and `notes.md`, and logs every call. Before using the result, `merge-pr.py`
checks the session's reported tools, MCP servers and permission mode, and checks that the
guard saw every tool call. If anything doesn't match, it stops. The prompt is
`merge-prompt.md`.
4. **Review.** For each conflict you see the PR's side, `dev`'s side and the resolution, plus
the agent's notes. Lines the agent starts with `UNCERTAIN:` or `SUSPICIOUS:`, leftover
markers and edits outside the conflict blocks are flagged. `[a]ccept`, `[e]dit` (your
`$EDITOR`, with vim modelines off), `[d]iff` against `dev`, or `[q]uit`. Nothing is
committed before you accept.
5. **Commit** the merge straight to git objects (first parent: the PR head; second: `dev`) as
`refs/pr-sandbox/<N>-merge`. It's reused on the next run as long as neither side has moved
(`REDO=1` to redo it).
6. **Sandbox** the merge with `sandbox-pr.sh --ref`: the usual risky-file triage and
confirmation, then the tests with your *current* `uv.lock`.

Then `make pr-review PR=<N>` reviews the PR and the report as usual. It also reads the merge's
conflict resolution (`resolution.diff`, i.e. `git show --cc`) and the agent's notes.
`make pr-push PR=<N>` pushes the merge commit to the contributor's branch after asking, so the
PR becomes mergeable on GitHub. If they didn't allow edits by maintainers, it offers to push
the merge as `pr-<N>-merged` and open a new PR from it. The contributor's commits stay in the
history either way.

Options: `AGENT=0` resolves in your editor instead of with the agent. A conflict it can't
handle (rename/delete, binary, symlink...) stops with instructions to merge by hand in a
throwaway worktree, then continue with `COMMIT=<sha>`. A `uv.lock` conflict is resolved by
taking `dev`'s lockfile: run `uv lock` afterwards if the PR changed dependencies.

To test a stale PR exactly as written instead (against the `dev` it was built on), use
`make pr-sandbox PR=<N> DEPS=merge-base`. `uv.lock` and `pyproject.toml` are then taken from
the PR's merge-base, which is still your own history, never the PR's. An old lockfile may
lack wheels for the default Python, so add `OPTS="--python 3.14"`.

## CI

- **`pr-sandbox-monitor.yml`** runs the same thing on every PR (`--monitor-only`: it fails on
Expand Down
71 changes: 71 additions & 0 deletions scripts/pr_sandbox/merge-guard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""PreToolUse hook for the conflict-resolving agent started by merge-pr.py.

Usage (set by merge-pr.py in the agent's --settings): merge-guard.py FILES_DIR LOG_FILE

The agent runs with --restricted and --tools Read,Edit,Write,Glob,Grep, so it has no shell and
no network tools. This hook is the backstop, and it also lets merge-pr.py check that the
agent's settings were applied (an entry in LOG_FILE for every tool call):
- only Read, Glob and Grep inside FILES_DIR are allowed
- only Edit and Write of FILES_DIR/conflicts/* and FILES_DIR/notes.md are allowed
- every other tool, path or mode is blocked (exit 2: the call is refused and stderr goes to the agent)
"""
import json
import os
import sys

READ_TOOLS = {"Read", "Glob", "Grep"}
WRITE_TOOLS = {"Edit", "Write"}
BLOCKED_MODES = {"auto", "bypassPermissions"}


def inside(path, root):
path = os.path.realpath(path)
return path == root or path.startswith(root + os.sep)


def decide(event, files_dir):
tool = event.get("tool_name", "")
args = event.get("tool_input") or {}
if event.get("permission_mode") in BLOCKED_MODES:
return f"tool use is blocked in '{event.get('permission_mode')}' mode"
cwd = event.get("cwd") or files_dir
if tool in READ_TOOLS:
path = args.get("file_path") if tool == "Read" else args.get("path") or cwd
if not isinstance(path, str) or not inside(os.path.join(cwd, path), files_dir):
return f"{tool} is only allowed inside {files_dir}"
pattern = args.get("pattern", "") if tool == "Glob" else args.get("glob", "")
if isinstance(pattern, str) and (pattern.startswith(("/", "~")) or ".." in pattern):
return f"{tool} patterns must stay inside {files_dir}"
return None
if tool in WRITE_TOOLS:
path = args.get("file_path")
if not isinstance(path, str):
return f"{tool} needs a file_path"
path = os.path.realpath(os.path.join(cwd, path))
conflicts = os.path.join(files_dir, "conflicts")
if os.path.dirname(path) == conflicts or path == os.path.join(files_dir, "notes.md"):
return None
return f"{tool} is only allowed on conflicts/* and notes.md"
return f"{tool or 'this tool'} is not available in this session: only Read, Glob, Grep, Edit and Write"


def main():
files_dir, log_file = os.path.realpath(sys.argv[1]), sys.argv[2]
try:
event = json.load(sys.stdin)
except ValueError:
event = {}
if not isinstance(event, dict):
event = {}
reason = decide(event, files_dir)
with open(log_file, "a") as log:
log.write(json.dumps({"tool": event.get("tool_name"), "input": event.get("tool_input"),
"blocked": reason}) + "\n")
if reason:
print(f"Blocked: {reason}. Don't look for workarounds; note what you needed in notes.md.",
file=sys.stderr)
sys.exit(2)


if __name__ == "__main__":
main()
Loading
Loading