Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(sandbox): support partial clone repos in workspace population (#58073)

Sandy Spicer8f36553e2eed
diff --git a/Dockerfile.sandbox b/Dockerfile.sandbox
index 2bf853985855..f5ba4d8f91a5 100644
--- a/Dockerfile.sandbox
+++ b/Dockerfile.sandbox
@@ -36,12 +36,20 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
pkg-config \
postgresql-client \
protobuf-compiler \
+ sudo \
tmux \
unzip \
vim \
zlib1g-dev \
&& rm -rf /var/lib/apt/lists/*
+# Personal image layers run install snippets as the sandbox user.
+# NOPASSWD sudo is available as an escape hatch for recipes that need
+# system-wide install (apt-get, /usr writes). Prefer ~/.local for
+# anything that can install per-user; reach for sudo when it can't.
+RUN echo "sandbox ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/sandbox \
+ && chmod 0440 /etc/sudoers.d/sandbox
+
# --- Rarely changes: Rust toolchain + sqlx-cli ---
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --no-modify-path \
&& chmod -R a+rwx /usr/local/cargo /usr/local/rustup
diff --git a/bin/sandbox b/bin/sandbox
index 593ff3ef79e7..5972b3654e0d 100755
--- a/bin/sandbox
+++ b/bin/sandbox
@@ -36,6 +36,9 @@ except ImportError:
print(" Or activate the flox environment first.", file=sys.stderr)
sys.exit(1)
+import sandbox_tools
+from sandbox_tools import TOOLS_FILE, Tool, ToolsError
+
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
@@ -43,14 +46,39 @@ except ImportError:
REPO_ROOT = Path(__file__).resolve().parent.parent
COMPOSE_FILE = REPO_ROOT / "docker-compose.sandbox.yml"
PROFILES_FILE = REPO_ROOT / "docker-compose.profiles.yml"
-HOST_GIT_DIR = REPO_ROOT / ".git"
GIT_HELPER_IMAGE = "alpine/git:latest"
SANDBOX_ORIGIN_URL = "[email protected]:PostHog/posthog.git"
+
+def _host_git_dir() -> Path:
+ """Path to mount as /host-git for the in-container clone helper.
+
+ For a regular checkout this is `<repo>/.git`. In a git worktree, that
+ path is a gitdir pointer file rather than a directory, so we resolve
+ the common .git dir via `rev-parse --git-common-dir` instead. The
+ in-container clone only needs refs/objects, which both layouts expose
+ from the common dir.
+ """
+ git_path = REPO_ROOT / ".git"
+ if git_path.is_dir():
+ return git_path
+ common = subprocess.run(
+ ["git", "-C", str(REPO_ROOT), "rev-parse", "--git-common-dir"],
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+ return Path(common).resolve()
+
REGISTRY_DIR = Path.home() / ".posthog-sandboxes"
REGISTRY_FILE = REGISTRY_DIR / "registry.json"
CONFIG_FILE = REGISTRY_DIR / "config.json"
+# Checked-in repository catalog of vetted tool recipes (gh, gt, etc.).
+# `sandbox tools add <name>` picks up entries by name.
+CATALOG_FILE = REPO_ROOT / "bin/sandbox-tools.yaml"
+
PORT_BASE = 48001
INFRA_SERVICES = [
@@ -669,8 +697,15 @@ def compose(
check: bool = True,
capture: bool = False,
profiles: list[str] | None = None,
+ use_tools: bool = True,
) -> subprocess.CompletedProcess:
"""Run `docker compose` with sandbox env vars."""
+ tool_auth_flag: list[str] = []
+ if use_tools and (tools := sandbox_tools.load_user_tools()):
+ dockerfile = sandbox_tools.write_user_dockerfile(tools)
+ override = sandbox_tools.write_user_image_compose(dockerfile=dockerfile)
+ tool_auth_flag = ["-f", str(override)]
+
profile_flags: list[str] = []
for p in profiles or []:
profile_flags.extend(["--profile", p])
@@ -685,6 +720,7 @@ def compose(
str(COMPOSE_FILE),
"-f",
str(PROFILES_FILE),
+ *tool_auth_flag,
*profile_flags,
*args,
],
@@ -712,6 +748,16 @@ def clear_volume(volume: str) -> None:
docker_volume_run(volume, "find /data -mindepth 1 -delete")
+def _is_partial_clone() -> bool:
+ """Check if the host repo is a partial clone (has promisor remote)."""
+ result = run(
+ ["git", "config", "--get", "remote.origin.promisor"],
+ check=False,
+ capture=True,
+ )
+ return result.returncode == 0 and result.stdout.strip() == "true"
+
+
def _populate_workspace_volume(
volume_name: str,
branch: str,
@@ -725,10 +771,19 @@ def _populate_workspace_volume(
Fetches by ref name (not bare SHA) because --depth only works with named
refs over file:// transport. Runs as sandbox user so files have correct ownership.
+
+ For partial clones (--filter=blob:none), uses filtered fetches from the
+ host .git for commits + trees, and a separate HTTPS promisor remote for
+ blob lazy-fetching so the sandbox can work without SSH auth popups.
"""
uid = os.getuid()
gid = os.getgid()
+ partial = _is_partial_clone()
+ if partial:
+ # Enable filtered fetches over file:// transport.
+ run(["git", "config", "uploadpack.allowFilter", "true"], capture=True)
+
run(["docker", "volume", "create", volume_name], capture=True)
# Chown so the non-root clone can write.
@@ -748,19 +803,38 @@ def _populate_workspace_volume(
)
# file:// transport avoids CVE-2022-39253 symlink following.
+ # For partial clones, --filter=blob:none skips blobs that upload-pack
+ # can't serve; a separate HTTPS promisor remote handles blob lazy-fetching.
script = r"""
set -e
git init -q -b "$BRANCH" /workspace
cd /workspace
GIT="git -c safe.directory=/host-git -c protocol.file.allow=always"
- $GIT fetch --depth=50 --no-tags file:///host-git "$BRANCH_REF"
+ if [ "$USE_FILTER" = "true" ]; then
+ FILTER="--filter=blob:none"
+ else
+ FILTER=""
+ fi
+
+ $GIT fetch --depth=50 --no-tags $FILTER file:///host-git "$BRANCH_REF"
git update-ref "refs/heads/$BRANCH" "$BRANCH_SHA"
git update-ref refs/sandbox/start "$BRANCH_SHA"
+
+ if [ "$USE_FILTER" = "true" ]; then
+ # HTTPS promisor remote for blob lazy-fetching (public, no auth).
+ # Kept separate from origin so blobs don't trigger SSH prompts.
+ git remote add github-https https://github.com/PostHog/posthog
+ git config remote.github-https.promisor true
+ git config remote.github-https.partialclonefilter blob:none
+ fi
+
git reset --hard
+ git remote add origin "$ORIGIN_URL"
+
if [ -n "$BASE_SHA" ]; then
- $GIT fetch --depth=1 --no-tags file:///host-git "$BASE_SHA"
+ $GIT fetch --depth=1 --no-tags $FILTER file:///host-git "$BASE_SHA"
git update-ref "refs/remotes/origin/$BASE_BRANCH" "$BASE_SHA"
fi
# Set origin/<branch> so `sandbox destroy` can detect unpushed commits.
@@ -768,11 +842,10 @@ def _populate_workspace_volume(
# Skip fetch if same as branch tip (already local); a redundant
# --depth=1 fetch would clobber the depth=50 shallow history.
if [ "$ORIGIN_BRANCH_SHA" != "$BRANCH_SHA" ]; then
- $GIT fetch --depth=1 --no-tags file:///host-git "$ORIGIN_BRANCH_SHA"
+ $GIT fetch --depth=1 --no-tags $FILTER file:///host-git "$ORIGIN_BRANCH_SHA"
fi
git update-ref "refs/remotes/origin/$BRANCH" "$ORIGIN_BRANCH_SHA"
fi
- git remote add origin "$ORIGIN_URL"
"""
run(
@@ -790,7 +863,7 @@ def _populate_workspace_volume(
"-e",
"GIT_LFS_SKIP_SMUDGE=1",
"-v",
- f"{HOST_GIT_DIR}:/host-git:ro",
+ f"{_host_git_dir()}:/host-git:ro",
"-v",
f"{volume_name}:/workspace",
"-e",
@@ -807,6 +880,8 @@ def _populate_workspace_volume(
f"ORIGIN_BRANCH_SHA={origin_branch_sha or ''}",
"-e",
f"ORIGIN_URL={SANDBOX_ORIGIN_URL}",
+ "-e",
+ f"USE_FILTER={'true' if partial else 'false'}",
GIT_HELPER_IMAGE,
"-c",
script,
@@ -1000,6 +1075,7 @@ def init_cache_from_master() -> None:
"-e",
"SANDBOX_MODE=cache-init",
"app",
+ use_tools=False,
)
info("Snapshotting databases...")
@@ -1088,7 +1164,7 @@ def check_migration_staleness(branch_sha: str) -> str | None:
"-v",
f"{DB_CACHE_VOLUME}:/cache:ro",
"-v",
- f"{HOST_GIT_DIR}:/host-git:ro",
+ f"{_host_git_dir()}:/host-git:ro",
"-e",
f"BRANCH_SHA={branch_sha}",
"--entrypoint",
@@ -1318,6 +1394,7 @@ def cmd_create(branch: str, base_branch: str = "master") -> None:
raise
container = f"{project}-app-1"
+ _seed_tool_auth(container, sandbox_tools.load_user_tools())
health_url = f"http://localhost:{port}/_health"
_attach_with_health_poll(container, health_url)
@@ -1668,6 +1745,138 @@ def cmd_rebuild_cache() -> None:
init_cache_from_master()
+# ---------------------------------------------------------------------------
+# Tools subcommand (manages ~/.posthog-sandboxes/tools.yaml)
+# ---------------------------------------------------------------------------
+
+
+def _prompt_lines(prompt_text: str, prompt_help: str, *, strip: bool = False) -> list[str]:
+ print(prompt_text)
+ print(prompt_help)
+ lines: list[str] = []
+ while True:
+ try:
+ line = input("> ")
+ except EOFError:
+ break
+ if strip:
+ line = line.strip()
+ if not line:
+ break
+ lines.append(line)
+ return lines
+
+
+def _print_tool_summary(tool: Tool, *, indent: str = " ") -> None:
+ print(f"{indent}{tool.name}")
+ if tool.install and (snippet := tool.install.strip()):
+ print(f"{indent} install:")
+ for line in snippet.splitlines():
+ print(f"{indent} {line}")
+ for c in tool.copy:
+ print(f"{indent} copy: {c.source} -> {c.target}")
+
+
+def _tools_list() -> None:
+ tools = sandbox_tools.load_user_tools()
+ catalog = sandbox_tools.load_catalog(CATALOG_FILE)
+ configured_names = {t.name for t in tools}
+
+ if tools:
+ print(f"Tools defined in {TOOLS_FILE}")
+ print()
+ for t in tools:
+ _print_tool_summary(t)
+ print()
+ else:
+ print(f"No tools configured in {TOOLS_FILE}.")
+ print()
+
+ if catalog:
+ print(f"Available recipes in {CATALOG_FILE.relative_to(REPO_ROOT)}:")
+ print(" (use `sandbox tools add <name>` to pull one into your tools.yaml)")
+ print()
+ for name in sorted(catalog):
+ entry = catalog[name]
+ marker = " [installed]" if name in configured_names else ""
+ print(f" {name}{marker}: {entry.description or ''}")
+ print()
+
+
+def _confirm(prompt: str, *, default_yes: bool = True) -> bool:
+ suffix = "[Y/n]" if default_yes else "[y/N]"
+ answer = input(f"{prompt} {suffix} ").strip().lower()
+ if not answer:
+ return default_yes
+ return answer in ("y", "yes")
+
+
+def _tools_add(args) -> None:
+ tools = sandbox_tools.load_user_tools()
+ if any(t.name == args.name for t in tools):
+ fatal(f"Tool '{args.name}' is already defined. Run 'sandbox tools remove {args.name}' first.")
+
+ explicit = args.install is not None or args.copy
+ catalog_hit = None if explicit else sandbox_tools.load_catalog(CATALOG_FILE).get(args.name)
+
+ if catalog_hit:
+ print(f"\n'{catalog_hit.name}' is in the sandbox tool catalog:")
+ if catalog_hit.description:
+ print(f" {catalog_hit.description}")
+ _print_tool_summary(catalog_hit)
+ if not _confirm("\nAdd this recipe to your tools.yaml?"):
+ info("Aborted.")
+ sys.exit(0)
+ new_tool = Tool(name=catalog_hit.name, install=catalog_hit.install, copy=list(catalog_hit.copy))
+ elif explicit:
+ copy_entries = [sandbox_tools.parse_tool_copy(c, source_label=f"'{args.name}' copy entry") for c in args.copy or []]
+ new_tool = Tool(name=args.name, install=args.install, copy=copy_entries)
+ else:
+ install_lines = _prompt_lines(
+ f"\nWhat install command(s) does '{args.name}' need?",
+ " Runs as the sandbox user at image build time. Use `sudo` for apt-get etc.\n"
+ " Multi-line allowed. Empty line to finish.",
+ )
+ install = "\n".join(install_lines).strip() or None
+ copy_strs = _prompt_lines(
+ f"\nWhere does '{args.name}' store auth/config on your host?",
+ " Absolute paths, one per line, blank when done. Most tools use ~/.config/<name>.",
+ strip=True,
+ )
+ copy_entries = [sandbox_tools.parse_tool_copy(c, source_label=f"'{args.name}' copy entry") for c in copy_strs]
+ new_tool = Tool(name=args.name, install=install, copy=copy_entries)
+
+ tools.append(new_tool)
+ sandbox_tools.save_user_tools(tools)
+ success(f"Added '{new_tool.name}' to {TOOLS_FILE}.")
+ print("Next `sandbox create` will pick it up (image rebuilds once).")
+
+
+def _tools_remove(name: str) -> None:
+ tools = sandbox_tools.load_user_tools()
+ remaining = [t for t in tools if t.name != name]
+ if len(remaining) == len(tools):
+ warn(f"No tool named '{name}' in {TOOLS_FILE}.")
+ return
+ sandbox_tools.save_user_tools(remaining)
+ success(f"Removed '{name}' from {TOOLS_FILE}.")
+ if remaining:
+ print("Next `sandbox create` will rebuild the personal image without it.")
+ else:
+ print("tools.yaml now empty; future sandboxes will use the base image directly.")
+
+
+def cmd_tools(args) -> None:
+ if args.tools_command == "list":
+ _tools_list()
+ elif args.tools_command == "add":
+ _tools_add(args)
+ elif args.tools_command == "remove":
+ _tools_remove(args.name)
+ else:
+ fatal("Run `sandbox tools --help` for usage.")
+
+
def cmd_nuke() -> None:
warn("Destroying all sandboxes and clearing cache...")
registry = Registry()
@@ -1696,6 +1905,39 @@ def _require_registered(registry: Registry, branch: str) -> SandboxEntry:
return entry
+def _seed_tool_auth(container: str, tools: list[Tool]) -> None:
+ """One-shot `docker cp` of tools.yaml copy entries into the new container.
+
+ Runs at create time only; the container owns the files after that so
+ tokens refreshed inside survive restarts.
+ """
+ for tool in tools:
+ for c in tool.copy:
+ src = Path(c.source).expanduser()
+ tgt = sandbox_tools.expand_sandbox_path(c.target)
+ if not src.exists():
+ continue
+ # mkdir as the sandbox user — docker exec defaults to root, and a
+ # root-owned parent dir would block the sandbox user from writing
+ # into it later (e.g. JetBrains under ~/.config). docker cp still
+ # lands root-owned, hence the chown below.
+ run(
+ [
+ "docker",
+ "exec",
+ "-u",
+ f"{os.getuid()}:{os.getgid()}",
+ container,
+ "mkdir",
+ "-p",
+ str(Path(tgt).parent),
+ ],
+ capture=True,
+ )
+ run(["docker", "cp", str(src), f"{container}:{tgt}"], capture=True)
+ run(["docker", "exec", container, "chown", "-R", "sandbox:sandbox", tgt], capture=True)
+
+
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
@@ -1758,6 +2000,35 @@ examples:
sub.add_parser("rebuild-cache", help="Rebuild the database cache from master")
sub.add_parser("nuke", help="Destroy all sandboxes and clear the cache")
+ tools_parser = sub.add_parser(
+ "tools",
+ help="Manage user-defined CLI tools and host auth paths",
+ description=(
+ "Manage ~/.posthog-sandboxes/tools.yaml. Additional CLIs baked "
+ "into your personal sandbox image and host auth paths copied in "
+ "at sandbox-create time."
+ ),
+ )
+ tools_sub = tools_parser.add_subparsers(dest="tools_command")
+ tools_sub.add_parser("list", help="Show configured tools and image status")
+ tools_add_p = tools_sub.add_parser(
+ "add",
+ help="Add a tool (interactive by default; --install/--copy for scripting)",
+ )
+ tools_add_p.add_argument("name")
+ tools_add_p.add_argument(
+ "--install",
+ help="Non-interactive: install snippet to run at image build time",
+ )
+ tools_add_p.add_argument(
+ "--copy",
+ action="append",
+ default=[],
+ help="Non-interactive: host path to copy into the sandbox $HOME (repeatable)",
+ )
+ tools_remove_p = tools_sub.add_parser("remove", help="Remove a tool")
+ tools_remove_p.add_argument("name")
+
return parser
@@ -1788,6 +2059,7 @@ def main() -> None:
"logs": lambda: cmd_logs(args.branch),
"rebuild-cache": cmd_rebuild_cache,
"nuke": cmd_nuke,
+ "tools": lambda: cmd_tools(args),
}
try:
@@ -1795,6 +2067,8 @@ def main() -> None:
except (KeyboardInterrupt, EOFError):
print()
sys.exit(130)
+ except ToolsError as e:
+ fatal(str(e))
except subprocess.CalledProcessError as e:
cmd_str = " ".join(str(a) for a in e.cmd)
error(f"Command failed (exit {e.returncode}): {cmd_str}")
diff --git a/bin/sandbox-entrypoint.py b/bin/sandbox-entrypoint.py
index 9ad513dd036d..6f6c35fe72d6 100644
--- a/bin/sandbox-entrypoint.py
+++ b/bin/sandbox-entrypoint.py
@@ -31,7 +31,11 @@ from pathlib import Path
from textwrap import dedent
WORKSPACE = Path("/workspace")
-SANDBOX_HOME = Path("/tmp/sandbox-home")
+# The sandbox user's $HOME. The base image creates this user at runtime (it's
+# UID-agnostic and shared); the per-user tools image creates it at build time.
+# Both must agree on this path, so it is mirrored by SANDBOX_HOME_IN_CONTAINER
+# in bin/sandbox_tools.py — keep the two in sync.
+SANDBOX_HOME = Path("/home/sandbox")
PROGRESS_FILE = Path("/tmp/sandbox-progress")
# Shown in tmux status bar, polled every 2s by tmux.sandbox.conf.
@@ -402,6 +406,18 @@ def setup_jetbrains_background() -> None:
if pid != 0:
return # Parent continues
+ # The child must never return to the caller. If an exception unwinds past
+ # os.fork(), run_setup's "JetBrains is non-fatal" guard catches it and the
+ # forked child then falls through and re-runs the rest of run_setup,
+ # spawning a duplicate phrocs window. Always terminate the child here.
+ try:
+ _run_jetbrains_child(idea_script, data_dir_name)
+ except Exception:
+ traceback.print_exc()
+ os._exit(0)
+
+
+def _run_jetbrains_child(idea_script: Path, data_dir_name: str) -> None:
# Child: redirect stdio to log so late writes don't clobber the tmux prompt.
log_path = "/tmp/sandbox-jetbrains.log"
log_fd = os.open(log_path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o644)
@@ -490,7 +506,6 @@ def setup_jetbrains_background() -> None:
)
info(f"{data_dir_name} backend ready")
- os._exit(0)
def _setup_user_env() -> None:
diff --git a/bin/sandbox-tools.yaml b/bin/sandbox-tools.yaml
new file mode 100644
index 000000000000..e546ec9196c5
--- /dev/null
+++ b/bin/sandbox-tools.yaml
@@ -0,0 +1,43 @@
+# Checked-in catalog of optional CLI tools that `./bin/sandbox tools add <name>`
+# can drop into a contributor's personal sandbox image. Entries here are not
+# automatically installed: users opt in by name. Each user's actual selection
+# lives in their own ~/.posthog-sandboxes/tools.yaml.
+#
+# Schema (per entry):
+# name required - matches the argument to `sandbox tools add`
+# description required - one-liner shown by `sandbox tools list`
+# install optional - shell script run as the sandbox user at image
+# build time; prefer user-mode install, sudo
+# (NOPASSWD) is available when actually needed
+# copy optional - host paths copied into the sandbox $HOME at
+# create time (short form for paths under $HOME,
+# long form `{source, target}` for system paths).
+# One-way snapshot at create time; sandbox edits
+# do not write back to the host
+#
+# When adding a new tool to the catalog:
+# 1. Author the install snippet against the current base image (run
+# `sandbox tools add <name> --install ... --test` locally to verify).
+# 2. List the host config paths the tool reads at runtime under `copy`.
+# Missing host paths are skipped silently, so it's fine to include
+# paths users may not have populated yet.
+# 3. Keep entries alphabetical by `name` for stable diffs.
+
+tools:
+ - name: gh
+ description: 'GitHub CLI (cli.github.com): repo browsing, PR review, gh auth share'
+ install: |
+ GH_VERSION=2.92.0
+ ARCH=$(dpkg --print-architecture)
+ mkdir -p ~/.local
+ curl -fsSL "https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_${ARCH}.tar.gz" \
+ | tar -xz --strip-components=1 -C ~/.local
+ copy:
+ - ~/.config/gh
+
+ - name: gt
+ description: 'Graphite CLI (graphite.dev): stacked PRs and review workflow'
+ install: |
+ npm install -g @withgraphite/graphite-cli@stable
+ copy:
+ - ~/.config/graphite
diff --git a/bin/sandbox_tools.py b/bin/sandbox_tools.py
new file mode 100644
index 000000000000..8e3f0397fb30
--- /dev/null
+++ b/bin/sandbox_tools.py
@@ -0,0 +1,191 @@
+"""Pure data layer for tools.yaml: schema, parsing, persistence, and the
+generated artifacts (compose override + user Dockerfile). No docker calls,
+no interactive prompts, no side effects at import. Callers wrap ToolsError
+with their own error reporter.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import yaml
+
+REGISTRY_DIR = Path.home() / ".posthog-sandboxes"
+TOOLS_FILE = REGISTRY_DIR / "tools.yaml"
+TOOL_AUTH_COMPOSE_FILE = REGISTRY_DIR / "docker-compose.tool-auth.yml"
+USER_DOCKERFILE = REGISTRY_DIR / "Dockerfile.user"
+
+SANDBOX_DOCKERFILE = Path(__file__).resolve().parent.parent / "Dockerfile.sandbox"
+
+# In-sandbox $HOME. Must stay in sync with SANDBOX_HOME in
+# bin/sandbox-entrypoint.py; this is what ~ resolves to inside the container.
+SANDBOX_HOME_IN_CONTAINER = "/home/sandbox"
+
+
+def expand_sandbox_path(raw: str) -> str:
+ """Expand ~ / ~/foo to the sandbox $HOME path. Everything else passes through."""
+ if raw == "~":
+ return SANDBOX_HOME_IN_CONTAINER
+ if raw.startswith("~/"):
+ return f"{SANDBOX_HOME_IN_CONTAINER}/{raw[2:]}"
+ return raw
+
+
+class ToolsError(Exception):
+ """Raised on any malformed tools.yaml or catalog entry."""
+
+
+@dataclass
+class ToolCopy:
+ # Stored exactly as written in tools.yaml. ~ expands per side at copy time:
+ # host via Path.expanduser(), container via expand_sandbox_path().
+ source: str
+ target: str
+
+
+@dataclass
+class Tool:
+ name: str
+ install: str | None = None
+ copy: list[ToolCopy] = field(default_factory=list)
+ # Catalog-only metadata. None in user tools.yaml; populated when loaded
+ # from bin/sandbox-tools.yaml. save_user_tools never persists it.
+ description: str | None = None
+
+
+class _BlockLiteralDumper(yaml.SafeDumper):
+ # Scoped subclass so the str representer below doesn't mutate yaml.SafeDumper globally.
+ pass
+
+
+def _block_literal_str(dumper: yaml.SafeDumper, data: str) -> yaml.ScalarNode:
+ if "\n" in data:
+ return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")
+ return dumper.represent_scalar("tag:yaml.org,2002:str", data)
+
+
+_BlockLiteralDumper.add_representer(str, _block_literal_str)
+
+
+def parse_tool_copy(entry: object, *, source_label: str) -> ToolCopy:
+ """Short form (one string used for both sides) or long form ({source, target})."""
+ if isinstance(entry, str):
+ return ToolCopy(source=entry, target=entry)
+ if isinstance(entry, dict):
+ return ToolCopy(source=str(entry["source"]), target=str(entry["target"]))
+ raise ToolsError(f"{source_label}: invalid copy entry {entry!r} (expected string or mapping).")
+
+
+def _parse_entry(raw: dict, *, label: str) -> Tool:
+ # Migration guard: 'mounts' was renamed to 'copy' in a recent commit.
+ if "mounts" in raw:
+ raise ToolsError(
+ f"{label} uses 'mounts:' which was renamed to 'copy:'. "
+ "Edit the YAML key (the field semantics are unchanged)."
+ )
+ name = raw.get("name")
+ if not isinstance(name, str) or not name.strip():
+ raise ToolsError(f"{label}: 'name' is required and must be a non-empty string.")
+ copy = [parse_tool_copy(c, source_label=f"{label}.copy[{i}]") for i, c in enumerate(raw.get("copy") or [])]
+ return Tool(name=name, install=raw.get("install"), copy=copy, description=raw.get("description") or None)
+
+
+def _load_tools(path: Path) -> list[Tool]:
+ if not path.is_file():
+ return []
+ raw = yaml.safe_load(path.read_text()) or {}
+ tools: list[Tool] = []
+ seen: set[str] = set()
+ for i, entry in enumerate(raw.get("tools") or []):
+ tool = _parse_entry(entry, label=f"{path}: tools[{i}]")
+ if tool.name in seen:
+ raise ToolsError(f"{path}: duplicate tool name {tool.name!r}.")
+ seen.add(tool.name)
+ tools.append(tool)
+ return tools
+
+
+def load_user_tools() -> list[Tool]:
+ return _load_tools(TOOLS_FILE)
+
+
+def load_catalog(catalog_file: Path) -> dict[str, Tool]:
+ # Catalog Tool instances have `description` set; user tools.yaml does not.
+ return {t.name: t for t in _load_tools(catalog_file)}
+
+
+def _format_copy(c: ToolCopy) -> str | dict[str, str]:
+ return c.source if c.source == c.target else {"source": c.source, "target": c.target}
+
+
+def save_user_tools(tools: list[Tool]) -> None:
+ entries: list[dict] = []
+ for t in tools:
+ entry: dict = {"name": t.name}
+ if t.install is not None:
+ entry["install"] = t.install if t.install.endswith("\n") else t.install + "\n"
+ if t.copy:
+ entry["copy"] = [_format_copy(c) for c in t.copy]
+ entries.append(entry)
+ TOOLS_FILE.parent.mkdir(parents=True, exist_ok=True)
+ TOOLS_FILE.write_text(
+ yaml.dump(
+ {"tools": entries},
+ Dumper=_BlockLiteralDumper,
+ sort_keys=False,
+ default_flow_style=False,
+ indent=2,
+ )
+ )
+
+
+def write_user_dockerfile(tools: list[Tool], *, out: Path = USER_DOCKERFILE) -> Path:
+ # Inlines the base Dockerfile and appends a RUN block per tool. Docker's
+ # BuildKit layer cache shares the base content across users by content,
+ # so there is no separate base-image tag to manage.
+ #
+ # Creates the sandbox user at build time with home = SANDBOX_HOME_IN_CONTAINER
+ # (the same path the entrypoint uses at runtime) so `npm install -g` etc. and
+ # ~ resolve consistently. The entrypoint's create_sandbox_user is idempotent:
+ # it skips when this build-time user already exists.
+ home = SANDBOX_HOME_IN_CONTAINER
+ parts = [
+ SANDBOX_DOCKERFILE.read_text().rstrip(),
+ "\n\n# --- Personal tool layers (generated from ~/.posthog-sandboxes/tools.yaml) ---\n",
+ "ARG SANDBOX_UID\nARG SANDBOX_GID\n\n",
+ "RUN groupadd -g ${SANDBOX_GID} sandbox 2>/dev/null || true \\\n",
+ f" && useradd -u ${{SANDBOX_UID}} -g ${{SANDBOX_GID}} -d {home} -m -s /bin/bash sandbox\n\n",
+ "USER sandbox\n",
+ f"ENV NPM_CONFIG_PREFIX={home}/.npm-global\n",
+ f"ENV PATH={home}/.npm-global/bin:{home}/.local/bin:${{PATH}}\n",
+ f"RUN mkdir -p {home}/.npm-global/bin {home}/.local/bin\n\n",
+ ]
+ for t in tools:
+ snippet = (t.install or "").strip()
+ if not snippet:
+ continue
+ parts.append(f"# Tool: {t.name}\n")
+ parts.append("RUN <<'__POSTHOG_SANDBOX_EOF__'\nset -e\n")
+ parts.append(snippet + "\n")
+ parts.append("__POSTHOG_SANDBOX_EOF__\n\n")
+ parts.append("USER root\n")
+
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text("".join(parts))
+ return out
+
+
+def write_user_image_compose(*, dockerfile: Path) -> Path:
+ # Override that points `build.dockerfile` at the per-user Dockerfile
+ # generated from tools.yaml. Rewritten before every `docker compose`
+ # call; tools.yaml is the source of truth so there's no cache to
+ # invalidate.
+ TOOL_AUTH_COMPOSE_FILE.parent.mkdir(parents=True, exist_ok=True)
+ with open(TOOL_AUTH_COMPOSE_FILE, "w") as f:
+ yaml.safe_dump(
+ {"services": {"app": {"build": {"dockerfile": str(dockerfile)}}}},
+ f,
+ sort_keys=False,
+ )
+ return TOOL_AUTH_COMPOSE_FILE
diff --git a/docker-compose.sandbox.yml b/docker-compose.sandbox.yml
index d3674cbfb306..792b9c006d93 100644
--- a/docker-compose.sandbox.yml
+++ b/docker-compose.sandbox.yml
@@ -122,9 +122,16 @@ services:
- app
app:
+ # Base build. When the user has tools.yaml entries, bin/sandbox
+ # generates a Dockerfile.user that layers tool installs on top and
+ # writes an override (docker-compose.tool-auth.yml) that swaps
+ # build.dockerfile to point at it.
build:
context: .
dockerfile: Dockerfile.sandbox
+ args:
+ SANDBOX_UID: '${SANDBOX_UID:-1000}'
+ SANDBOX_GID: '${SANDBOX_GID:-1000}'
restart: on-failure
init: true
# mprocs (used by bin/start) requires a TTY