: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(sandbox): unblock claude and add --full-clone option (#59161)
Sandy Spicerdd92b1c664fb
diff --git a/bin/sandbox b/bin/sandboxindex 5972b3654e0d..bac1e548a8c5 100755--- a/bin/sandbox+++ b/bin/sandbox@@ -18,7 +18,9 @@ import sysimport jsonimport timeimport fcntl+import shleximport shutil+import getpassimport argparseimport platformimport textwrap@@ -36,8 +38,11 @@ except ImportError:print(" Or activate the flox environment first.", file=sys.stderr)sys.exit(1)+import sandbox_env+import sandbox_mcpimport sandbox_tools-from sandbox_tools import TOOLS_FILE, Tool, ToolsError+from sandbox_addons import AddonError+from sandbox_tools import TOOLS_FILE, Tool# ---------------------------------------------------------------------------# Constants@@ -48,6 +53,8 @@ COMPOSE_FILE = REPO_ROOT / "docker-compose.sandbox.yml"PROFILES_FILE = REPO_ROOT / "docker-compose.profiles.yml"GIT_HELPER_IMAGE = "alpine/git:latest"SANDBOX_ORIGIN_URL = "[email protected]:PostHog/posthog.git"+# In-container workspace path; must match WORKSPACE in bin/sandbox-entrypoint.py.+SANDBOX_WORKSPACE = "/workspace"@functools.cache@@ -79,6 +86,10 @@ CONFIG_FILE = REGISTRY_DIR / "config.json"# `sandbox tools add <name>` picks up entries by name.CATALOG_FILE = REPO_ROOT / "bin/sandbox-tools.yaml"+# Checked-in catalog of vetted remote MCP servers (posthog, etc.).+# `sandbox mcp add <name>` picks up entries by name.+MCP_CATALOG_FILE = REPO_ROOT / "bin/sandbox-mcps.yaml"+PORT_BASE = 48001INFRA_SERVICES = [@@ -342,8 +353,18 @@ def project_name(slug: str) -> str:# --- Host auth paths ---+def _file_or_devnull(path: Path) -> str:+ """Host path for an optional bind-mount or env_file, or /dev/null when absent."""+ return str(path) if path.is_file() else "/dev/null"++def _claude_auth_dir() -> str:- """Assemble only the Claude Code files needed to authenticate and configure."""+ """Assemble the Claude Code files needed to authenticate and configure.++ Ships a complete CLAUDE.md (your global one plus a generated section+ describing this sandbox's env vars and tools), so the container only has to+ bind-mount the finished file — no assembly in the entrypoint.+ """auth_dir = REGISTRY_DIR / "claude-auth"auth_dir.mkdir(parents=True, exist_ok=True)claude_dir = Path.home() / ".claude"@@ -352,6 +373,22 @@ def _claude_auth_dir() -> str:if src.exists():shutil.copy2(src, auth_dir / filename)+ # Build the staged CLAUDE.md from your global one plus this sandbox's+ # provisioned env vars and tools. Names + comments only; secret values+ # never enter CLAUDE.md (parse_env_comments doesn't even read them).+ host_md = claude_dir / "CLAUDE.md"+ base = host_md.read_text() if host_md.is_file() else ""+ context = sandbox_env.render_context_markdown(+ sandbox_env.parse_env_comments(),+ sandbox_tools.resolved_tools(CATALOG_FILE),+ )+ staged_md = auth_dir / "CLAUDE.md"+ parts = [p for p in (base.rstrip(), context.rstrip()) if p]+ if parts:+ staged_md.write_text("\n\n".join(parts) + "\n")+ elif staged_md.exists():+ staged_md.unlink()+# Claude Code credentials: check disk first, fall back to macOS keychain.creds_file = auth_dir / ".credentials.json"creds_src = claude_dir / ".credentials.json"@@ -369,6 +406,31 @@ def _claude_auth_dir() -> str:return str(auth_dir)+def _claude_json_file() -> str:+ """Build the sandbox's .claude.json on the host; return its path or /dev/null.++ Starts from your ~/.claude.json, drops the host installMethod (Claude is+ npm-installed in the sandbox, not the native binary the host config points+ at), and merges the resolved MCP servers under the /workspace project so+ they load without an approval prompt. Done here so the entrypoint just+ copies a finished file instead of assembling it. Written 0600 since merged+ MCP server configs may carry auth tokens.+ """+ host_json = Path.home() / ".claude.json"+ config = json.loads(host_json.read_text()) if host_json.is_file() else {}+ config.pop("installMethod", None)+ servers = sandbox_mcp.resolve_servers()+ if servers:+ workspace = config.setdefault("projects", {}).setdefault(SANDBOX_WORKSPACE, {})+ workspace.setdefault("mcpServers", {}).update(servers)+ if not config:+ return "/dev/null"+ out = REGISTRY_DIR / "claude.json"+ out.write_text(json.dumps(config, indent=2) + "\n")+ out.chmod(0o600)+ return str(out)++def _ssh_authorized_keys_path() -> str:"""Collect SSH public keys into a file that can be mounted into containers."""keys_file = REGISTRY_DIR / "authorized_keys"@@ -661,15 +723,19 @@ def _host_compose_env() -> dict[str, str]:"""Env vars from host state, cached to avoid re-probing per sandbox in cmd_list."""config = _load_config()ide = config.get("jetbrains")- claude_json = Path.home() / ".claude.json"host_gitconfig = Path.home() / ".gitconfig"env = {"SANDBOX_SSH_AUTHORIZED_KEYS": _ssh_authorized_keys_path(),"SANDBOX_CLAUDE_AUTH": _claude_auth_dir(),"SANDBOX_UID": str(os.getuid()),"SANDBOX_GID": str(os.getgid()),- "SANDBOX_CLAUDE_JSON": str(claude_json) if claude_json.is_file() else "/dev/null",- "SANDBOX_HOST_GITCONFIG": str(host_gitconfig) if host_gitconfig.is_file() else "/dev/null",+ # Finalized .claude.json (installMethod stripped, MCP servers merged+ # under /workspace), built on the host so the entrypoint just copies it.+ "SANDBOX_CLAUDE_JSON": _claude_json_file(),+ # User secrets (KEY=value); compose env_file injects the values into the+ # sandbox env. Names + comments are baked into CLAUDE.md by _claude_auth_dir.+ "SANDBOX_ENV_FILE": _file_or_devnull(sandbox_env.ENV_FILE),+ "SANDBOX_HOST_GITCONFIG": _file_or_devnull(host_gitconfig),# Signing paths — entrypoint rewrites the copied gitconfig to point here."SANDBOX_HOST_GIT_SIGNINGKEY": _host_git_config_file("user.signingkey"),"SANDBOX_HOST_ALLOWED_SIGNERS": _host_git_config_file("gpg.ssh.allowedSignersFile"),@@ -766,8 +832,13 @@ def _populate_workspace_volume(base_sha: str | None,origin_branch_sha: str | None = None,branch_ref: str = "",+ full_clone: bool = False,) -> None:- """Populate volume with a shallow clone checked out to branch_sha.+ """Populate volume with a clone checked out to branch_sha.++ Shallow by default. When full_clone is set, fetches omit --depth so the+ sandbox keeps the complete git history (git log/blame/bisect work, push+ has full ancestry) at the cost of more disk and a slower clone.Fetches by ref name (not bare SHA) because --depth only works with namedrefs over file:// transport. Runs as sandbox user so files have correct ownership.@@ -817,7 +888,17 @@ def _populate_workspace_volume(FILTER=""fi- $GIT fetch --depth=50 --no-tags $FILTER file:///host-git "$BRANCH_REF"+ # A full clone keeps complete history (no .git/shallow); the default+ # trades history for a smaller, faster clone.+ if [ "$FULL_CLONE" = "true" ]; then+ BRANCH_DEPTH=""+ REF_DEPTH=""+ else+ BRANCH_DEPTH="--depth=50"+ REF_DEPTH="--depth=1"+ fi++ $GIT fetch $BRANCH_DEPTH --no-tags $FILTER file:///host-git "$BRANCH_REF"git update-ref "refs/heads/$BRANCH" "$BRANCH_SHA"git update-ref refs/sandbox/start "$BRANCH_SHA"@@ -834,15 +915,16 @@ def _populate_workspace_volume(git remote add origin "$ORIGIN_URL"if [ -n "$BASE_SHA" ]; then- $GIT fetch --depth=1 --no-tags $FILTER file:///host-git "$BASE_SHA"+ $GIT fetch $REF_DEPTH --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.if [ -n "$ORIGIN_BRANCH_SHA" ]; then- # Skip fetch if same as branch tip (already local); a redundant- # --depth=1 fetch would clobber the depth=50 shallow history.+ # Skip fetch if same as branch tip (already local); in shallow+ # mode a redundant --depth=1 fetch would also clobber the deeper+ # shallow history.if [ "$ORIGIN_BRANCH_SHA" != "$BRANCH_SHA" ]; then- $GIT fetch --depth=1 --no-tags $FILTER file:///host-git "$ORIGIN_BRANCH_SHA"+ $GIT fetch $REF_DEPTH --no-tags $FILTER file:///host-git "$ORIGIN_BRANCH_SHA"figit update-ref "refs/remotes/origin/$BRANCH" "$ORIGIN_BRANCH_SHA"fi@@ -882,6 +964,8 @@ def _populate_workspace_volume(f"ORIGIN_URL={SANDBOX_ORIGIN_URL}","-e",f"USE_FILTER={'true' if partial else 'false'}",+ "-e",+ f"FULL_CLONE={'true' if full_clone else 'false'}",GIT_HELPER_IMAGE,"-c",script,@@ -1250,22 +1334,28 @@ def _wait_for_clickhouse(project: str, timeout: int = 120) -> None:capture=True,)if result.returncode != 0:- fatal(f"ClickHouse did not become ready within {timeout}s. Container logs may reveal the cause.")+ raise RuntimeError(f"ClickHouse did not become ready within {timeout}s. Container logs may reveal the cause.")-def _restore_and_start(+def _restore_databases(project: str,port: int,use_cache: bool,profiles: list[str] | None = None,) -> None:- """Restore databases from cache (if available) and bring up the stack."""+ """Bring up infra and restore databases from cache. Runs detached, behind the+ already-started app container, so the Claude window is available immediately.++ The app's setup window waits for these to be ready (and, when use_cache, for+ the ClickHouse restore to land) before it migrates.+ """if not use_cache:- info("Building and starting containers...")- compose(project, port, "up", "-d", "--build", capture=True, profiles=profiles)+ info("Starting infrastructure...")+ compose(project, port, "up", "-d", capture=True, profiles=profiles)return- # Restore postgres from volume snapshot+ # Postgres restores from a raw data-dir copy, which must land before the db+ # container boots and reads it.info("Restoring Postgres from cache...")run([@@ -1284,8 +1374,6 @@ def _restore_and_start(capture=True,)- # Start infra first — we need ClickHouse up before restoring its backup,- # and both must finish before the app runs migrations.info("Starting infrastructure...")compose(project, port, "up", "-d", *INFRA_SERVICES, capture=True, profiles=profiles)@@ -1309,7 +1397,10 @@ def _restore_and_start(error("ClickHouse restore failed:")for line in (result.stderr or "").strip().splitlines():print(f" {line}")- fatal("Run `sandbox rebuild-cache` if the cache is corrupt, or retry with `sandbox create`.")+ raise RuntimeError(+ "ClickHouse restore failed. Run `sandbox rebuild-cache` if the cache is corrupt, "+ "or retry with `sandbox create`."+ )info("ClickHouse restored.")# Drop the cached DuckLake catalog — the extension version in the cache@@ -1322,9 +1413,15 @@ def _restore_and_start(capture=True,)- # Now start the app + proxy on top of restored infra- info("Building and starting app...")- compose(project, port, "up", "-d", "--build", capture=True, profiles=profiles)+ # The RESTORE above is synchronous and has fully landed — tell the app's+ # setup window (same container) it's safe to migrate. Without this it would+ # wait on a probe that can pass mid-restore.+ run(["docker", "exec", f"{project}-app-1", "sh", "-c", "printf done > /tmp/sandbox-restore-status"], capture=True)++ # Bring up the proxy (and any profile-gated services) now that infra is ready;+ # the app container is already running.+ info("Starting proxy and supporting services...")+ compose(project, port, "up", "-d", capture=True, profiles=profiles)# ---------------------------------------------------------------------------@@ -1332,7 +1429,7 @@ def _restore_and_start(# ----------------------------------------------------------------------------def cmd_create(branch: str, base_branch: str = "master") -> None:+def cmd_create(branch: str, base_branch: str = "master", *, full_clone: bool = False) -> None:registry = Registry()slug = slugify(branch)project = project_name(slug)@@ -1381,24 +1478,92 @@ def cmd_create(branch: str, base_branch: str = "master") -> None:# volume, compose project, registry entry), so wrap in rollback.try:volume = workspace_volume_name(project)+ if full_clone:+ info("Full clone requested — fetching complete git history (slower, more disk).")info(f"Populating workspace volume {volume} with branch {branch}...")- _populate_workspace_volume(volume, branch, branch_sha, base_branch, base_sha, origin_branch_sha, branch_ref)+ _populate_workspace_volume(+ volume,+ branch,+ branch_sha,+ base_branch,+ base_sha,+ origin_branch_sha,+ branch_ref,+ full_clone=full_clone,+ )profiles = resolve_docker_profiles(intents)if profiles:info(f"Docker profiles: {', '.join(profiles)}")- _restore_and_start(project, port, use_cache, profiles=profiles)+ # Start the app container alone (--no-deps skips the db/ch/kafka health+ # gates) so the Claude window is up in seconds. Infra + DB restore run+ # in the background below; the setup window waits for them before migrating.+ os.environ["SANDBOX_USE_CACHE"] = "1" if use_cache else "0"+ info("Starting Claude window...")+ compose(project, port, "up", "-d", "--build", "--no-deps", "app", capture=True, profiles=profiles)except BaseException:error(f"Sandbox create failed — tearing down '{project}'.")cmd_destroy(branch, force=True)raise+ _spawn_db_restore(branch, use_cache)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)+def _spawn_db_restore(branch: str, use_cache: bool) -> None:+ """Run infra bringup + DB restore in a detached process so the foreground can+ attach to Claude immediately. Output goes to a log for post-mortems; failures+ surface in the sandbox's setup window when its DB wait times out.+ """+ log_path = REGISTRY_DIR / f"{slugify(branch)}-db-restore.log"+ log = open(log_path, "w")+ subprocess.Popen(+ [sys.executable, __file__, "_db-restore", branch, "1" if use_cache else "0"],+ stdin=subprocess.DEVNULL,+ stdout=log,+ stderr=log,+ start_new_session=True,+ )+++def _mark_restore_failed(container: str, reason: str) -> None:+ """Record the restore failure in the app container so its setup window stops+ waiting on the database and surfaces the error, instead of timing out.++ Best-effort. Skips writing if the status is already "done": a failure after+ the DB restore succeeded (e.g. proxy bringup) must not turn a ready sandbox+ into an error for the setup window.+ """+ script = (+ '[ "$(cat /tmp/sandbox-restore-status 2>/dev/null)" = done ] || '+ f"printf %s {shlex.quote(reason)} > /tmp/sandbox-restore-status"+ )+ run(["docker", "exec", container, "sh", "-c", script], check=False, capture=True)+++def cmd_db_restore(branch: str, use_cache: bool) -> None:+ """Internal: detached worker spawned by `create` to bring up infra + restore.++ Runs detached, so its output only reaches a log file. On failure it writes+ the reason into the app container, where the setup window is blocking on the+ database; otherwise that window would wait out its full timeout in silence.+ """+ entry = Registry().get(branch)+ if entry is None:+ fatal(f"No sandbox registered for '{branch}'.")+ project = project_name(entry.slug)+ profiles = resolve_docker_profiles(entry.intents)+ try:+ _restore_databases(project, entry.port, use_cache, profiles=profiles)+ except BaseException as e: # includes SystemExit from any fatal() below+ reason = str(e).strip() or f"Database restore failed ({type(e).__name__})."+ _mark_restore_failed(f"{project}-app-1", reason)+ raise++def cmd_start(branch: str) -> None:registry = Registry()entry = _require_registered(registry, branch)@@ -1767,48 +1932,72 @@ def _prompt_lines(prompt_text: str, prompt_help: str, *, strip: bool = False) ->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 _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_list() -> None:- tools = sandbox_tools.load_user_tools()- catalog = sandbox_tools.load_catalog(CATALOG_FILE)- configured_names = {t.name for t in tools}+# --- Shared addon CLI verbs (tools + MCP) ---+- if tools:- print(f"Tools defined in {TOOLS_FILE}")+def _addon_list(*, noun, title, user_file, catalog_file, configured, catalog, summary) -> None:+ """List configured entries then catalog recipes, marking the [added] ones.++ `configured`/`catalog` map name -> entry; `summary(entry)` yields detail lines.+ """+ if configured:+ print(f"{title} configured for sandbox use ({user_file}):")print()- for t in tools:- _print_tool_summary(t)+ for entry in configured.values():+ for line in summary(entry):+ print(line)print()else:- print(f"No tools configured in {TOOLS_FILE}.")+ print(f"No {title.lower()} configured for sandbox use ({user_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()+ print(f"Recipes available to install from the repository ({catalog_file.relative_to(REPO_ROOT)}):")+ print(f" (use `sandbox {noun} add <name>` to add one)")+ for name in sorted(catalog):+ marker = " [added]" if name in configured else ""+ print(f" {name}{marker}: {catalog[name].description or ''}")-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 _addon_remove(*, noun, user_file, name, load, save) -> None:+ items = load()+ remaining = [item for item in items if item.name != name]+ if len(remaining) == len(items):+ warn(f"No {noun} named '{name}' in {user_file}.")+ return+ save(remaining)+ success(f"Removed {noun} '{name}'. Next `sandbox create` will apply the change.")+++# --- Tools ---+++def _tool_summary(tool: Tool, *, indent: str = " ") -> list[str]:+ lines = [f"{indent}{tool.name}"]+ if tool.install and (snippet := tool.install.strip()):+ lines.append(f"{indent} install:")+ lines.extend(f"{indent} {line}" for line in snippet.splitlines())+ lines.extend(f"{indent} copy: {c.source} -> {c.target}" for c in tool.copy)+ return lines+++def _tools_list() -> None:+ _addon_list(+ noun="tools",+ title="Tools",+ user_file=TOOLS_FILE,+ catalog_file=CATALOG_FILE,+ configured={t.name: t for t in sandbox_tools.load_user_tools()},+ catalog=sandbox_tools.load_catalog(CATALOG_FILE),+ summary=_tool_summary,+ )def _tools_add(args) -> None:@@ -1823,7 +2012,8 @@ def _tools_add(args) -> None: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)+ for line in _tool_summary(catalog_hit):+ print(line)if not _confirm("\nAdd this recipe to your tools.yaml?"):info("Aborted.")sys.exit(0)@@ -1853,17 +2043,13 @@ def _tools_add(args) -> None: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.")+ _addon_remove(+ noun="tool",+ user_file=TOOLS_FILE,+ name=name,+ load=sandbox_tools.load_user_tools,+ save=sandbox_tools.save_user_tools,+ )def cmd_tools(args) -> None:@@ -1877,6 +2063,129 @@ def cmd_tools(args) -> None:fatal("Run `sandbox tools --help` for usage.")+# --- Remote MCP servers ---+#+# Catalog entries declare their auth via ${secret} placeholders that+# `sandbox mcp add <name>` fills in; a one-off `add <name> <url>` assumes Bearer+# auth. Stored in mcps.yaml (0600), resolved to JSON at create time.+++def _mcp_summary(mcp: sandbox_mcp.Mcp, *, indent: str = " ") -> list[str]:+ auth = " (auth)" if mcp.server.get("headers") else ""+ return [f"{indent}{mcp.name}: {mcp.server.get('url')}{auth}"]+++def _ensure_env_var(name: str, comment: str) -> None:+ """Ensure `name` is set in sandbox.env, prompting (hidden) for it if missing.++ Lets `mcp add` store an MCP's token in the one secrets file in a single step+ instead of making you edit sandbox.env separately.+ """+ if name in {n for n, _ in sandbox_env.parse_env_comments()}:+ info(f"Using {name} from {sandbox_env.ENV_FILE.name}.")+ return+ value = getpass.getpass(f" {name} (hidden): ").strip()+ if not value:+ fatal(f"'{name}' is required.")+ sandbox_env.append_var(name, value, comment)+ success(f"Saved {name} to {sandbox_env.ENV_FILE}.")+++def _mcp_add(name: str, url: str | None) -> None:+ mcps = sandbox_mcp.load_user_mcps()+ if any(m.name == name for m in mcps):+ fatal(f"MCP '{name}' already exists. Run 'sandbox mcp remove {name}' first.")++ if url:+ # One-off server not in the catalog. Reference an env var for auth so the+ # token lives in sandbox.env, not mcps.yaml.+ server: dict = {"type": "http", "url": url}+ var = input("Auth env var name (blank for none): ").strip()+ if var:+ _ensure_env_var(var, f"Auth token for the {name} MCP.")+ server["headers"] = {"Authorization": f"Bearer ${{{var}}}"}+ else:+ catalog = sandbox_mcp.load_catalog(MCP_CATALOG_FILE)+ entry = catalog.get(name)+ if not entry:+ available = ", ".join(sorted(catalog)) or "(none)"+ fatal(f"'{name}' is not in the catalog (available: {available}). For a one-off: sandbox mcp add {name} <url>")+ for var in entry.env:+ _ensure_env_var(var, f"Used by the {entry.name} MCP.")+ server = entry.server++ mcps.append(sandbox_mcp.Mcp(name=name, server=server))+ sandbox_mcp.save_user_mcps(mcps)+ success(f"Added MCP '{name}' ({server['url']}).")+ print("Next `sandbox create` will register it with Claude in the sandbox.")+++def _mcp_list() -> None:+ _addon_list(+ noun="mcp",+ title="MCP servers",+ user_file=sandbox_mcp.MCP_FILE,+ catalog_file=MCP_CATALOG_FILE,+ configured={m.name: m for m in sandbox_mcp.load_user_mcps()},+ catalog=sandbox_mcp.load_catalog(MCP_CATALOG_FILE),+ summary=_mcp_summary,+ )+++def cmd_mcp(args) -> None:+ if args.mcp_command == "add":+ _mcp_add(args.name, args.url)+ elif args.mcp_command == "remove":+ _addon_remove(+ noun="MCP",+ user_file=sandbox_mcp.MCP_FILE,+ name=args.name,+ load=sandbox_mcp.load_user_mcps,+ save=sandbox_mcp.save_user_mcps,+ )+ else:+ _mcp_list()+++# --- Env vars (secrets) ---+++def _open_in_editor(path: Path) -> None:+ editor = os.environ.get("VISUAL") or os.environ.get("EDITOR")+ if not editor:+ for candidate in ("sensible-editor", "nano", "vi"):+ if shutil.which(candidate):+ editor = candidate+ break+ if not editor:+ info(f"No $VISUAL/$EDITOR set and no nano/vi found. Edit it directly: {path}")+ return+ # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-tainted-env-args.dangerous-subprocess-use-tainted-env-args -- local dev CLI launching the developer's own $VISUAL/$EDITOR on a local file+ subprocess.run([*shlex.split(editor), str(path)], check=False)+++def cmd_env(args) -> None:+ if args.env_command == "list":+ pairs = sandbox_env.parse_env_comments()+ if not pairs:+ print(f"No env vars configured ({sandbox_env.ENV_FILE}).")+ return+ print(f"Env vars provisioned to sandboxes ({sandbox_env.ENV_FILE}):")+ for name, comment in pairs:+ head = comment.splitlines()[0] if comment else ""+ print(f" {name}: {head}" if head else f" {name}")+ return++ path = sandbox_env.ensure_file()+ _open_in_editor(path)+ path.chmod(0o600)+ names = [name for name, _ in sandbox_env.parse_env_comments(path)]+ success(f"Saved {path} (mode 600).")+ if names:+ print(f" Vars: {', '.join(names)}")+ print(" Applies on the next `sandbox create` / `sandbox start`.")++def cmd_nuke() -> None:warn("Destroying all sandboxes and clearing cache...")registry = Registry()@@ -1952,6 +2261,7 @@ def build_parser() -> argparse.ArgumentParser:examples:sandbox create aspicer/cool-featuresandbox create aspicer/bugfix main+ sandbox create aspicer/cool-feature --full-clonesandbox lssandbox shell aspicer/cool-featuresandbox ssh aspicer/cool-feature@@ -1970,6 +2280,11 @@ examples:default="product_analytics",help="Comma-separated hogli intents (default: product_analytics)",)+ p.add_argument(+ "--full-clone",+ action="store_true",+ help="Clone full git history instead of shallow (more disk; enables git log/blame/bisect)",+ )for name, help_text in [("start", "Start a stopped sandbox"),@@ -2029,6 +2344,42 @@ examples:tools_remove_p = tools_sub.add_parser("remove", help="Remove a tool")tools_remove_p.add_argument("name")+ mcp_parser = sub.add_parser(+ "mcp",+ help="Manage remote MCP servers available to Claude in the sandbox",+ description=(+ "Manage ~/.posthog-sandboxes/mcps.yaml: remote MCP servers registered "+ "with Claude in every sandbox at create time. Tokens are prompted for "+ "and saved to sandbox.env; the server config references them via ${VAR}."+ ),+ )+ mcp_sub = mcp_parser.add_subparsers(dest="mcp_command")+ mcp_sub.add_parser("list", help="List configured MCP servers")+ mcp_add_p = mcp_sub.add_parser("add", help="Add a remote MCP server (prompts for its key, saved to sandbox.env)")+ mcp_add_p.add_argument("name")+ mcp_add_p.add_argument("url", nargs="?", help="URL for a one-off server not in the catalog (assumes Bearer auth)")+ mcp_remove_p = mcp_sub.add_parser("remove", help="Remove an MCP server")+ mcp_remove_p.add_argument("name")++ env_parser = sub.add_parser(+ "env",+ help="Edit the env vars (secrets) provisioned to your sandboxes",+ description=(+ "Manage ~/.posthog-sandboxes/sandbox.env. Each KEY=value is injected "+ "into every sandbox's environment; the agent uses them by reference "+ "($SLACK_TOKEN) and never sees the value. `# comment` lines above a KEY "+ "describe it to the agent in CLAUDE.md."+ ),+ )+ env_sub = env_parser.add_subparsers(dest="env_command")+ env_sub.add_parser("edit", help="Open the env file in $EDITOR (default action)")+ env_sub.add_parser("list", help="List configured env var names and descriptions")++ # Internal: detached infra-bringup/restore worker spawned by `create`.+ db_restore_p = sub.add_parser("_db-restore")+ db_restore_p.add_argument("branch")+ db_restore_p.add_argument("use_cache", choices=["0", "1"])+return parser@@ -2044,7 +2395,7 @@ def main() -> None:os.environ["SANDBOX_INTENTS"] = args.intentsdispatch = {- "create": lambda: cmd_create(args.branch, args.base_branch),+ "create": lambda: cmd_create(args.branch, args.base_branch, full_clone=args.full_clone),"start": lambda: cmd_start(args.branch),"stop": lambda: cmd_stop(args.branch),"destroy": lambda: cmd_destroy(args.branch, force=args.force),@@ -2060,6 +2411,9 @@ def main() -> None:"rebuild-cache": cmd_rebuild_cache,"nuke": cmd_nuke,"tools": lambda: cmd_tools(args),+ "mcp": lambda: cmd_mcp(args),+ "env": lambda: cmd_env(args),+ "_db-restore": lambda: cmd_db_restore(args.branch, args.use_cache == "1"),}try:@@ -2067,7 +2421,7 @@ def main() -> None:except (KeyboardInterrupt, EOFError):print()sys.exit(130)- except ToolsError as e:+ except AddonError as e:fatal(str(e))except subprocess.CalledProcessError as e:cmd_str = " ".join(str(a) for a in e.cmd)diff --git a/bin/sandbox-entrypoint.py b/bin/sandbox-entrypoint.pyindex 6f6c35fe72d6..5668700c9631 100644--- a/bin/sandbox-entrypoint.py+++ b/bin/sandbox-entrypoint.py@@ -20,11 +20,14 @@ from __future__ import annotationsimport osimport sys+import jsonimport statimport timeimport shutil+import socketimport tracebackimport subprocess+import urllib.requestfrom collections.abc import Callablefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom pathlib import Path@@ -41,6 +44,12 @@ PROGRESS_FILE = Path("/tmp/sandbox-progress")# Shown in tmux status bar, polled every 2s by tmux.sandbox.conf.STATUS_FILE = Path("/tmp/sandbox-status")+# The host's detached restore writes its status here: "done" once the (cache)+# ClickHouse RESTORE has fully landed, or a failure reason if it dies before the+# database is ready. The setup window waits for "done" before migrating and+# aborts on a failure reason instead of timing out. Written by bin/sandbox.+RESTORE_STATUS_FILE = Path("/tmp/sandbox-restore-status")+# ---------------------------------------------------------------------------# Helpers# ---------------------------------------------------------------------------@@ -113,6 +122,10 @@ def export_environment(uid: int, gid: int) -> None:"""Write env vars to /etc/environment and /etc/profile.d for SSH sessions."""extra_vars = {"HOME": str(SANDBOX_HOME),+ # flox sets VIRTUAL_ENV by sourcing the venv's activate; the sandbox+ # never activates. bin/hogli and bin/ruff.sh prefer it over PATH. Equal+ # to UV_PROJECT_ENVIRONMENT, so uv sync emits no mismatch warning.+ "VIRTUAL_ENV": "/cache/python","UV_CACHE_DIR": "/cache/uv","UV_LINK_MODE": "copy","XDG_CACHE_HOME": "/tmp/sandbox-cache",@@ -184,18 +197,73 @@ def start_sshd(uid: int, gid: int) -> None:log("sshd listening on port 2222")+def _strip_host_permissions(settings_path: Path) -> None:+ """Strip permission policy so host rules can't override sandbox bypass mode.++ deny survives bypass by design; defaultMode in settings.local.json would+ shadow bypassPermissions in settings.json. allow is moot under bypass.+ """+ if not settings_path.exists():+ return+ try:+ settings = json.loads(settings_path.read_text())+ except (OSError, json.JSONDecodeError):+ return+ perms = settings.get("permissions")+ if not isinstance(perms, dict):+ return+ perms.pop("allow", None)+ perms.pop("deny", None)+ perms.pop("defaultMode", None)+ if not perms:+ settings.pop("permissions", None)+ settings_path.write_text(json.dumps(settings, indent=2) + "\n")+++def _force_sandbox_claude_defaults(settings_path: Path) -> None:+ """Make the sandbox's Claude default to max effort + bypass permissions.++ The sandbox is a disposable, isolated container — the safety friction that+ justifies permission prompts on the host doesn't apply here, and the Claude+ window boots unattended in tmux. Plugins and theme survive the merge;+ allow/deny lists are stripped separately by _strip_host_permissions.+ """+ try:+ settings = json.loads(settings_path.read_text()) if settings_path.exists() else {}+ except (OSError, json.JSONDecodeError):+ settings = {}++ settings["effortLevel"] = "max"+ # Equivalent of --dangerously-skip-permissions; the second key suppresses+ # the one-time confirmation so the unattended tmux window doesn't block.+ settings.setdefault("permissions", {})["defaultMode"] = "bypassPermissions"+ settings["skipDangerousModePermissionPrompt"] = True+ # Auto-approve the repo's checked-in .mcp.json servers (phrocs, traffic-sim)+ # so they load on the unattended boot without the approval prompt.+ settings["enableAllProjectMcpServers"] = True++ settings_path.write_text(json.dumps(settings, indent=2) + "\n")++def copy_claude_auth(uid: int, gid: int) -> None:"""Copy Claude Code auth files into the sandbox home."""claude_dir = SANDBOX_HOME / ".claude"claude_dir.mkdir(parents=True, exist_ok=True)- for name in (".credentials.json", "settings.json", "settings.local.json"):+ for name in (".credentials.json", "settings.json", "settings.local.json", "CLAUDE.md"):src = Path(f"/tmp/claude-auth/{name}")if src.exists():shutil.copy2(src, claude_dir / name)+ _strip_host_permissions(claude_dir / "settings.json")+ _strip_host_permissions(claude_dir / "settings.local.json")+ _force_sandbox_claude_defaults(claude_dir / "settings.json")++ # bin/sandbox ships a finalized .claude.json (installMethod stripped, MCP+ # servers merged under the /workspace project); just place it. is_file()+ # skips the /dev/null mount used when there's nothing to ship.src = Path("/tmp/claude-auth.json")- if src.exists():+ if src.is_file():shutil.copy2(src, SANDBOX_HOME / ".claude.json")run(["chown", "-R", f"{uid}:{gid}", str(SANDBOX_HOME)])@@ -239,6 +307,8 @@ def root_phase() -> None:create_sandbox_user(uid, gid)# Must run before export_environment snapshots os.environ into /etc/profile.d.+ # The user's sandbox.env secrets are already in os.environ (compose env_file),+ # so export_environment propagates them to every shell and the Claude tree._configure_ssh_agent_env()export_environment(uid, gid)@@ -514,6 +584,8 @@ def _setup_user_env() -> None:os.environ.update({"HOME": str(SANDBOX_HOME),+ # Mirror export_environment so the tmux/claude tree gets VIRTUAL_ENV.+ "VIRTUAL_ENV": "/cache/python","UV_CACHE_DIR": "/cache/uv","UV_LINK_MODE": "copy","XDG_CACHE_HOME": "/tmp/sandbox-cache",@@ -598,6 +670,82 @@ def user_phase() -> None:sys.exit(1)+def _port_open(host: str, port: int) -> bool:+ try:+ with socket.create_connection((host, port), timeout=2):+ return True+ except OSError:+ return False+++def _clickhouse_ready() -> bool:+ """True once ClickHouse answers a trivial query over HTTP."""+ try:+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected -- URL is a hardcoded constant, no user-controlled value+ with urllib.request.urlopen("http://clickhouse:8123/", data=b"SELECT 1", timeout=3) as resp:+ return resp.read().strip() == b"1"+ except OSError:+ return False+++def _restore_status() -> str | None:+ """What the host's detached restore last wrote: "done", a failure reason, or+ None if it hasn't written yet. The setup window waits for "done" (cache+ creates) and aborts on a failure reason instead of timing out.+ """+ if RESTORE_STATUS_FILE.exists():+ return RESTORE_STATUS_FILE.read_text().strip() or None+ return None+++def _restore_failed_reason() -> str | None:+ """The failure reason if the restore reported one, else None ("done" is success)."""+ status = _restore_status()+ return status if status and status != "done" else None+++def _wait_for(+ label: str,+ ready: Callable[[], bool],+ timeout: int = 300,+ fail_check: Callable[[], str | None] | None = None,+) -> None:+ """Poll `ready` until true, updating the status bar; raise on timeout.++ `fail_check` returns a reason string to abort early. It's checked *after*+ `ready`, so a restore that already signalled success wins over a late failure.+ """+ _write_status(f"waiting for {label}")+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if ready():+ return+ if fail_check and (reason := fail_check()):+ raise RuntimeError(reason)+ time.sleep(2)+ raise RuntimeError(f"{label} not ready within {timeout}s")+++def _wait_for_databases() -> None:+ """Block until infra is ready before migrating.++ Postgres restores before its container boots, so a reachable db is already+ restored. ClickHouse restores onto a *running* server, and the database can+ appear mid-restore — so for a cache-backed create we wait for the "done" status+ the host writes once its synchronous RESTORE has fully landed, not on a probe.+ """+ _wait_for(+ "Postgres",+ lambda: run_quiet(["psql", "-h", "db", "-U", "posthog", "-d", "posthog", "-tAc", "SELECT 1"]).returncode == 0,+ fail_check=_restore_failed_reason,+ )+ if os.environ.get("SANDBOX_USE_CACHE") == "1":+ _wait_for("ClickHouse cache restore", lambda: _restore_status() == "done", fail_check=_restore_failed_reason)+ else:+ _wait_for("ClickHouse", _clickhouse_ready, fail_check=_restore_failed_reason)+ _wait_for("Kafka", lambda: _port_open("kafka", 9092), fail_check=_restore_failed_reason)++def run_setup() -> None:"""Tmux window 2: install deps, migrate, seed data, spawn phrocs, exec bash.@@ -605,27 +753,32 @@ def run_setup() -> None:so the user can diagnose. Claude keeps running in window 1 either way."""_setup_user_env()+ # The status file can linger in /tmp across a stop/start; clear it before+ # waiting so a stale "done"/failure from a previous boot can't trip this one.+ # On a cache create the host worker writes the fresh status later.+ RESTORE_STATUS_FILE.unlink(missing_ok=True)_write_status("setup starting")try:- # Kafka is health-gated by compose, safe to call early.- create_kafka_topics()-- def install_python_and_migrate() -> None:- install_python_deps()- _write_status("running migrations")- run(["python", "manage.py", "sandbox_migrate", "--progress-file", str(PROGRESS_FILE)])- _write_status("seeding demo data")- ensure_demo_data()-+ # Deps need no database, so install them while the host brings up and+ # restores infra in the background._run_parallel({- "python deps + migrations": install_python_and_migrate,+ "python deps": install_python_deps,"node deps": install_node_deps,"rust crates": fetch_rust_crates,})+ # Gate DB work on infra being ready (and the cache restore having landed)+ # so we never migrate a half-restored database.+ _wait_for_databases()+ create_kafka_topics()+ _write_status("running migrations")+ run(["python", "manage.py", "sandbox_migrate", "--progress-file", str(PROGRESS_FILE)])+ _write_status("seeding demo data")+ ensure_demo_data()+# generate_mprocs_config needs the hogli symlink created by install_python_deps.generate_mprocs_config()@@ -648,15 +801,21 @@ def run_setup() -> None:"\nSetup complete — see status bar for keybinding hints.\n",flush=True,)- except Exception:+ except Exception as e:traceback.print_exc()- _write_status("!! SETUP FAILED — see window 2")+ _write_status("!! SETUP FAILED. Ctrl-b 1 returns to claude")print( # noqa: T201- "\n\n!!! Setup failed — traceback above. This window is now a bash shell;"- "\n!!! claude is still running in window 1 against whatever managed to come up."- "\n!!! Re-run the failing step manually, then `tmux new-window bin/start --phrocs` when ready.\n",+ f"\n\n!!! Setup failed: {e}"+ "\n!!! Traceback above. This window is now a bash shell; claude is still running in window 1."+ "\n!!! Fix the issue, then `tmux new-window bin/start --phrocs` when ready.\n",flush=True,)+ # Pull the user's view to this window so the failure can't be missed,+ # but leave claude running in window 1, since they may already be working.+ # select before rename, so the "setup" target still resolves.+ tmux = ["tmux", "-L", "sandbox"]+ subprocess.run([*tmux, "select-window", "-t", "posthog:setup"])+ subprocess.run([*tmux, "rename-window", "-t", "posthog:setup", "⚠ SETUP FAILED"])# Exec into bash so this window stays usable (both success and failure).os.execvp("bash", ["bash", "-l"])diff --git a/bin/sandbox-mcps.yaml b/bin/sandbox-mcps.yamlnew file mode 100644index 000000000000..67c6cab20a8d--- /dev/null+++ b/bin/sandbox-mcps.yaml@@ -0,0 +1,26 @@+# Curated catalog of remote MCP servers that `./bin/sandbox mcp add <name>` can+# register in your sandbox. Opt in by name; your selection lives in+# ~/.posthog-sandboxes/mcps.yaml (only ${VAR} references, no tokens), never in git.+#+# Per entry:+# name required - the argument to `sandbox mcp add`+# description required - one-liner shown by `sandbox mcp list`+# env optional - env var names this server needs. `sandbox mcp add`+# prompts (hidden) for any not already in sandbox.env+# and stores them there; the server references them via+# ${VAR}, which Claude expands from the env at runtime.+# server required - the value Claude expects under mcpServers[name]:+# a remote server ({type: http, url, headers}).+#+# Keep entries alphabetical by `name` for stable diffs.++mcps:+ - name: posthog+ description: PostHog hosted MCP — insights, flags, errors, SQL+ env:+ - POSTHOG_PERSONAL_API_KEY+ server:+ type: http+ url: https://mcp.posthog.com/mcp+ headers:+ Authorization: 'Bearer ${POSTHOG_PERSONAL_API_KEY}'diff --git a/bin/sandbox-shims/tmux.sandbox.conf b/bin/sandbox-shims/tmux.sandbox.confindex fa867c157556..9da9353b6c87 100644--- a/bin/sandbox-shims/tmux.sandbox.conf+++ b/bin/sandbox-shims/tmux.sandbox.conf@@ -1,6 +1,16 @@# tmux server config for the sandbox container.# Loaded via `tmux -L sandbox -f /etc/tmux.sandbox.conf`.+# --- Truecolor (24-bit RGB) ---------------------------------------------++# What tmux reports to programs running inside it.+set -g default-terminal "tmux-256color"++# Advertise RGB for attaching clients so truecolor passes through. Wildcard+# because this server is attached from many different terminals, and virtually+# every modern emulator supports RGB. Scope to a specific $TERM if you must.+set -as terminal-features ",*:RGB"+# --- Beginner-friendly defaults -----------------------------------------# Mouse mode: click to select panes/windows, drag to resize, scroll with@@ -30,6 +40,10 @@ bind r source-file /etc/tmux.sandbox.conf \; display "Config reloaded"# --- Status bar ---------------------------------------------------------+# Dark bar with light text. Without this, tmux defaults to a green bar, and+# the gray inactive-tab text (below) is unreadable on green.+set -g status-style 'bg=colour236,fg=colour250'+# Surface setup progress in the status line so every window sees it.# /tmp/sandbox-status is written by the setup process at each phase.set -g status-interval 2@@ -40,9 +54,9 @@ set -g status-right-length 120set -g status-left '[#S] 'set -g status-left-length 40-# Make the active tab visually obvious: bold white text on a blue background.-# Inactive tabs are dim so the active one pops.-set -g window-status-current-style 'bg=blue,fg=white,bold'+# Make the active tab visually obvious: bold near-black text on a bright blue+# background. Inactive tabs are dim gray so the active one pops.+set -g window-status-current-style 'bg=colour39,fg=colour16,bold'set -g window-status-current-format ' #I:#W '-set -g window-status-style 'fg=colour244'+set -g window-status-style 'fg=colour245'set -g window-status-format ' #I:#W 'diff --git a/bin/sandbox-tools.yaml b/bin/sandbox-tools.yamlindex e546ec9196c5..22f1e236c26c 100644--- a/bin/sandbox-tools.yaml+++ b/bin/sandbox-tools.yaml@@ -41,3 +41,18 @@ tools:npm install -g @withgraphite/graphite-cli@stablecopy:- ~/.config/graphite++ - name: metabase+ description: 'Metabase SSO cookies for the query-clickhouse-via-metabase skill (hogli metabase:*, regions us/eu/dev)'+ copy:+ - ~/.config/posthog/metabase/cookie-us+ - ~/.config/posthog/metabase/cookie-eu+ - ~/.config/posthog/metabase/cookie-dev++ - name: opencode+ description: 'opencode (opencode.ai): terminal-based AI coding agent'+ install: |+ npm install -g opencode-ai+ copy:+ - ~/.config/opencode+ - ~/.local/share/opencode/auth.jsondiff --git a/bin/sandbox_addons.py b/bin/sandbox_addons.pynew file mode 100644index 000000000000..378ab32c9b5a--- /dev/null+++ b/bin/sandbox_addons.py@@ -0,0 +1,88 @@+"""Shared format for sandbox addons (tools, MCP servers): named entries chosen+from a checked-in YAML catalog into a per-user YAML file. Owns the read/write+plumbing, the registry path, and the error type; per-type schema and apply logic+live in sandbox_tools.py / sandbox_mcp.py.+"""++from __future__ import annotations++from collections.abc import Callable+from pathlib import Path+from typing import Protocol, TypeVar++import yaml++REGISTRY_DIR = Path.home() / ".posthog-sandboxes"+++class AddonError(Exception):+ """Raised on any malformed catalog or user-file entry."""+++class _Named(Protocol):+ name: str+++_T = TypeVar("_T", bound=_Named)+++class _BlockLiteralDumper(yaml.SafeDumper):+ """Renders multi-line strings as `|` blocks (e.g. tool install scripts)."""+++def _block_literal_str(dumper: yaml.SafeDumper, data: str) -> yaml.ScalarNode:+ style = "|" if "\n" in data else None+ return dumper.represent_scalar("tag:yaml.org,2002:str", data, style=style)+++_BlockLiteralDumper.add_representer(str, _block_literal_str)+++def load_named_entries(path: Path, section: str) -> list[dict]:+ """Read the `section:` list as raw dicts, validating unique non-empty names.++ Returns [] when the file is absent.+ """+ if not path.is_file():+ return []+ raw = yaml.safe_load(path.read_text()) or {}+ entries: list[dict] = []+ seen: set[str] = set()+ for i, entry in enumerate(raw.get(section) or []):+ label = f"{path}: {section}[{i}]"+ if not isinstance(entry, dict):+ raise AddonError(f"{label}: must be a mapping.")+ name = entry.get("name")+ if not isinstance(name, str) or not name.strip():+ raise AddonError(f"{label}: 'name' is required and must be a non-empty string.")+ if name in seen:+ raise AddonError(f"{path}: duplicate name {name!r}.")+ seen.add(name)+ entries.append(entry)+ return entries+++def save_named_entries(path: Path, section: str, entries: list[dict], *, mode: int | None = None) -> None:+ """Write `entries` under the `section:` key, preserving order and block scalars."""+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ yaml.dump(+ {section: entries},+ Dumper=_BlockLiteralDumper,+ sort_keys=False,+ default_flow_style=False,+ indent=2,+ )+ )+ if mode is not None:+ path.chmod(mode)+++def load_entries(path: Path, section: str, parse: Callable[[dict], _T]) -> list[_T]:+ """Parse each `section:` entry from a YAML file into a typed object."""+ return [parse(entry) for entry in load_named_entries(path, section)]+++def load_catalog(path: Path, section: str, parse: Callable[[dict], _T]) -> dict[str, _T]:+ """Like load_entries, but keyed by entry name for catalog lookups."""+ return {entry.name: entry for entry in load_entries(path, section, parse)}diff --git a/bin/sandbox_env.py b/bin/sandbox_env.pynew file mode 100644index 000000000000..809f92dafd22--- /dev/null+++ b/bin/sandbox_env.py@@ -0,0 +1,122 @@+"""Pure data layer for sandbox.env: parse the user's KEY=value secrets file+(with `# comment` descriptions) and render the agent-facing context block that+bin/sandbox appends to the sandbox CLAUDE.md. No docker calls, no secret values+in the output — parse_env_comments never even reads the values, so they cannot+leak into CLAUDE.md.+"""++from __future__ import annotations++from pathlib import Path++from sandbox_addons import REGISTRY_DIR++ENV_FILE = REGISTRY_DIR / "sandbox.env"++TEMPLATE = """\+# Secrets for your PostHog dev sandboxes, injected as environment variables.+#+# One KEY=value per line. The `# comment` lines directly above a KEY become the+# description the in-sandbox agent sees in its CLAUDE.md. The values are set in+# the sandbox environment but never shown to the agent: it uses them by+# reference (e.g. $SLACK_TOKEN), so they stay out of the transcript. Put a blank+# line between entries. Applies on the next `sandbox create` / `sandbox start`.+#+# Example (uncomment and fill in):+#+# # Slack token. Use by reference, e.g.:+# # curl -H "Authorization: Bearer $SLACK_TOKEN" https://slack.com/api/auth.test+# SLACK_TOKEN=xoxb-...+"""+++def ensure_file(path: Path = ENV_FILE) -> Path:+ """Create the secrets file with the commented template if absent (mode 0600)."""+ if not path.is_file():+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(TEMPLATE)+ path.chmod(0o600)+ return path+++def append_var(name: str, value: str, comment: str = "", path: Path = ENV_FILE) -> None:+ """Append a `# comment` + KEY=value block to the secrets file (mode 0600).++ Creates the file from the template first if needed. Callers append only vars+ that aren't already set, so this does not de-duplicate.+ """+ ensure_file(path)+ lines = ["", *(f"# {c}" for c in comment.splitlines()), f"{name}={value}"]+ with path.open("a") as f:+ f.write("\n".join(lines) + "\n")+ path.chmod(0o600)+++def parse_env_comments(path: Path = ENV_FILE) -> list[tuple[str, str]]:+ """Return (name, comment) for each KEY=value in a .env-style file.++ `# comment` lines directly above an assignment attach to it; a blank line+ resets the pending comment. Values are deliberately not returned: only the+ entrypoint reads the file for values, and they must never reach CLAUDE.md.+ """+ if not path.is_file():+ return []+ pairs: list[tuple[str, str]] = []+ pending: list[str] = []+ for raw in path.read_text().splitlines():+ line = raw.strip()+ if not line:+ pending = []+ continue+ if line.startswith("#"):+ pending.append(line.lstrip("#").strip())+ continue+ if line.startswith("export "):+ line = line[len("export ") :].lstrip()+ if "=" not in line:+ pending = []+ continue+ name = line.partition("=")[0].strip()+ if name:+ pairs.append((name, "\n".join(pending)))+ pending = []+ return pairs+++def render_context_markdown(env_vars: list[tuple[str, str]], tools: list[tuple[str, str]]) -> str:+ """Render provisioned env vars + tools into the CLAUDE.md context block.++ Lists env var names with their comments, never the values.+ """+ if not env_vars and not tools:+ return ""++ lines = [+ "## Sandbox environment",+ "",+ "You are running in an isolated PostHog dev sandbox. The items below are provisioned for you.",+ ]++ if env_vars:+ lines += [+ "",+ "### Secrets (environment variables)",+ "",+ "These are already set in your shell environment. Use them by reference "+ "(for example `$SLACK_TOKEN`); do not print, echo, or `cat` their values, "+ "and avoid `curl -v`, so the secrets stay out of the transcript.",+ "",+ ]+ for name, comment in env_vars:+ comment_lines = comment.splitlines()+ head = comment_lines[0] if comment_lines else ""+ lines.append(f"- `{name}`: {head}" if head else f"- `{name}`")+ lines += [f" {extra}" for extra in comment_lines[1:]]++ if tools:+ lines += ["", "### Installed CLI tools", ""]+ for name, desc in tools:+ desc = (desc or "").strip()+ lines.append(f"- `{name}`: {desc}" if desc else f"- `{name}`")++ return "\n".join(lines) + "\n"diff --git a/bin/sandbox_mcp.py b/bin/sandbox_mcp.pynew file mode 100644index 000000000000..aeca36318810--- /dev/null+++ b/bin/sandbox_mcp.py@@ -0,0 +1,55 @@+"""Remote MCP server schema for mcps.yaml: secret templating, persistence, and+the resolved JSON the sandbox entrypoint merges into Claude. Shares the+catalog/user-file YAML format with tools via sandbox_addons.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path++import sandbox_addons+from sandbox_addons import REGISTRY_DIR, AddonError++MCP_FILE = REGISTRY_DIR / "mcps.yaml"+++@dataclass+class Mcp:+ name: str+ server: dict # value Claude expects under mcpServers[name]+ # Catalog-only; never written to the user file.+ description: str | None = None+ # Env vars (set in sandbox.env) that this server's config references via ${VAR}.+ env: list[str] = field(default_factory=list)+++def _parse_entry(raw: dict) -> Mcp:+ # name presence/uniqueness is validated by sandbox_addons.load_named_entries.+ name = raw["name"]+ server = raw.get("server")+ if not isinstance(server, dict):+ raise AddonError(f"mcp {name!r}: 'server' is required and must be a mapping.")+ env = raw.get("env") or []+ if not isinstance(env, list) or not all(isinstance(s, str) for s in env):+ raise AddonError(f"mcp {name!r}: 'env' must be a list of strings.")+ return Mcp(name=name, server=server, description=raw.get("description") or None, env=env)+++def load_user_mcps() -> list[Mcp]:+ return sandbox_addons.load_entries(MCP_FILE, "mcps", _parse_entry)+++def load_catalog(catalog_file: Path) -> dict[str, Mcp]:+ return sandbox_addons.load_catalog(catalog_file, "mcps", _parse_entry)+++def save_user_mcps(mcps: list[Mcp]) -> None:+ # Servers reference secrets as ${VAR} (set in sandbox.env), so the file+ # itself holds no tokens.+ entries = [{"name": m.name, "server": m.server} for m in mcps]+ sandbox_addons.save_named_entries(MCP_FILE, "mcps", entries)+++def resolve_servers() -> dict[str, dict]:+ return {m.name: m.server for m in load_user_mcps()}diff --git a/bin/sandbox_tools.py b/bin/sandbox_tools.pyindex 8e3f0397fb30..5c41a1f592fb 100644--- a/bin/sandbox_tools.py+++ b/bin/sandbox_tools.py@@ -1,7 +1,8 @@"""Pure data layer for tools.yaml: schema, parsing, persistence, and thegenerated artifacts (compose override + user Dockerfile). No docker calls,-no interactive prompts, no side effects at import. Callers wrap ToolsError-with their own error reporter.+no interactive prompts, no side effects at import. Shares the catalog/user-file+YAML format with MCP servers via sandbox_addons; adds the tool-specific schema+and apply logic."""from __future__ import annotations@@ -10,8 +11,9 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathimport yaml+import sandbox_addons+from sandbox_addons import REGISTRY_DIR, AddonError-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"@@ -32,10 +34,6 @@ def expand_sandbox_path(raw: str) -> str:return raw-class ToolsError(Exception):- """Raised on any malformed tools.yaml or catalog entry."""--@dataclassclass ToolCopy:# Stored exactly as written in tools.yaml. ~ expands per side at copy time:@@ -54,65 +52,46 @@ class Tool: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).")+ raise AddonError(f"{source_label}: invalid copy entry {entry!r} (expected string or mapping).")-def _parse_entry(raw: dict, *, label: str) -> Tool:+def _parse_entry(raw: dict) -> Tool:+ # name presence/uniqueness is validated by sandbox_addons.load_named_entries.+ name = raw["name"]# 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:'. "+ raise AddonError(+ f"tool {name!r} 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 [])]+ copy = [parse_tool_copy(c, source_label=f"tool {name!r} 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)+ return sandbox_addons.load_entries(TOOLS_FILE, "tools", _parse_entry)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)}+ return sandbox_addons.load_catalog(catalog_file, "tools", _parse_entry)+++def resolved_tools(catalog_file: Path) -> list[tuple[str, str]]:+ """Return (name, description) for the user's selected tools.++ Descriptions come from the catalog, since the user tools.yaml doesn't store+ them; tools added ad hoc (not in the catalog) get an empty description.+ bin/sandbox uses this to list installed tools in the sandbox CLAUDE.md.+ """+ catalog = load_catalog(catalog_file)+ return [(t.name, (catalog[t.name].description if t.name in catalog else None) or "") for t in load_user_tools()]def _format_copy(c: ToolCopy) -> str | dict[str, str]:@@ -128,16 +107,7 @@ def save_user_tools(tools: list[Tool]) -> None: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,- )- )+ sandbox_addons.save_named_entries(TOOLS_FILE, "tools", entries)def write_user_dockerfile(tools: list[Tool], *, out: Path = USER_DOCKERFILE) -> Path:diff --git a/docker-compose.sandbox.yml b/docker-compose.sandbox.ymlindex cd5635156a1b..b304994ea64b 100644--- a/docker-compose.sandbox.yml+++ b/docker-compose.sandbox.yml@@ -169,13 +169,20 @@ services:# Sandbox uses the shared service-connection defaults but NOT .env.development —# the latter has host-side URLs (SESSION_RECORDING_V2_S3_ENDPOINT=localhost:8333,# OBJECT_STORAGE_PUBLIC_ENDPOINT=localhost:19000) that don't resolve inside the- # container. Dev runtime knobs (DEBUG, etc.) are set inline below.- env_file: .env.services+ # container. Dev runtime knobs (DEBUG, etc.) are set inline below. The user's+ # sandbox.env (resolved to a real path or /dev/null by bin/sandbox) injects+ # their secrets straight into the sandbox environment.+ env_file:+ - .env.services+ - ${SANDBOX_ENV_FILE:-/dev/null}environment:# --- Sandbox identity ---SANDBOX_UID: '${SANDBOX_UID:-1000}'SANDBOX_GID: '${SANDBOX_GID:-1000}'POSTHOG_SANDBOX: '1'+ # 1 during a cache-backed `create`: the setup window waits for the+ # background ClickHouse restore to land before migrating.+ SANDBOX_USE_CACHE: '${SANDBOX_USE_CACHE:-0}'SANDBOX_INTENTS: '${SANDBOX_INTENTS:-product_analytics}'DEBUG: '1'HOST_BIND: '0.0.0.0'