: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
feat(tasks): persist task tmp and home directories (#116989)
Alessandro Pogliaghif33e7e180661
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex a0c3d2f6cb06..a4ac2b76e4a5 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -161,6 +161,37 @@ atomically when accepting events or completion, rejecting stale senders with HTTand `stream_generation_mismatch`. The sender discards its buffer and stops on this code.Tokens issued before generation tracking remain valid only until the stream resets.+`TASKS_SANDBOX_PERSISTENT_FILESYSTEM_ENABLED` enables an experimental Modal layout+for default, autoresearch, and VM task templates. Task processes see `/tmp`, `/var/tmp`, and `/root` backed by+`/tmp/workspace/.posthog/task-filesystem`, so ordinary files at those paths enter+directory snapshots. Modal control processes keep their original filesystem view.+Agentsh, the setup wizard, dev-stack bootstrap, and preview services enter the task view; Docker must+start there so bind mounts resolve the same paths. Fresh credential files remain+outside the saved directories. Claude's pinned session settings resolve to a private+runtime directory, and the one-use Codex token is staged under `/run`.+Base images seed the persistent home outside the workspace during build, preserving+ownership. Custom images and dev-stack bakes refresh that seed after warming their+caches. Activation moves the seed into the workspace without copying it; disabled+tasks leave it out of directory snapshots, and versioned restores keep their saved+home. Fresh tasks using older images without a home seed keep the provider view+until those images are rebuilt. Image-bake sandboxes keep the provider view, and wizard output+lives under `/tmp/workspace/.posthog/wizard-cloud-run`.+Namespace entry preserves the caller's working directory. Health and capability+checks run in the provider view, while bundled-skill cleanup runs in the task view.+Cleanup uses a fixed system PATH and absolute system binaries. Helper uploads+use the caller's execution timeout.+Automatic dev-stack bootstrap uses a fresh Docker config directory under `/run`.+Launch preparation uses a fixed system PATH and the image's absolute agentsh path.++Snapshots carry a layout version. Restoring that version initializes the task view+even when the setting is disabled, while legacy workspace snapshots stay readable.+Unversioned restores keep their original layout even when enabled, so existing+files remain accessible without copying a home at startup.+Missing namespaces and unknown versions fail startup. This layout covers files;+processes, runtime sockets, system package changes, and service data outside these+directories still need their own recovery. Keep it disabled until the checkpoint+handoff and required service recovery are validated together.+## Running via the UIThis is very minimal at the moment, but the tasks page can be used to see whatdiff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex ac01c27a185c..d9de917ef9c7 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -188,6 +188,12 @@ TASKS_SANDBOX_MEMORY_WATCHDOG_ENABLED: bool = get_from_env(type_cast=str_to_bool,)+TASKS_SANDBOX_PERSISTENT_FILESYSTEM_ENABLED: bool = get_from_env(+ "TASKS_SANDBOX_PERSISTENT_FILESYSTEM_ENABLED",+ False,+ type_cast=str_to_bool,+)+# Event-count threshold for the above; 0 relies on Temporal's is_continue_as_new_suggested().TASKS_CONTINUE_AS_NEW_HISTORY_THRESHOLD: int = get_from_env("TASKS_CONTINUE_AS_NEW_HISTORY_THRESHOLD", 4000, type_cast=intdiff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.pyindex 5fa95f235871..d99034ab8fd7 100644--- a/products/tasks/backend/logic/services/agent_server_launcher.py+++ b/products/tasks/backend/logic/services/agent_server_launcher.py@@ -74,7 +74,7 @@ AGENT_SERVER_HEALTH_DURATION_PREFIX = "__posthog_agent_health_ms="# The agent-server reads this fd once at boot and closes it, so processes it starts never see the# token. The launch shell opens the file on fd 3 and deletes it before the server starts.CODEX_RUN_TOKEN_FD = 3-CODEX_RUN_TOKEN_FILE = "/tmp/agent-codex-run-token"+CODEX_RUN_TOKEN_FILE = "/run/posthog/agent-codex-run-token"AGENT_SERVER_FREE_PORT_SCRIPT = ("agent_server_pids() { for p in $(pgrep -f '[a]gent-server'); do "@@ -87,7 +87,6 @@ AGENT_SERVER_FREE_PORT_SCRIPT = (AGENT_SERVER_LAUNCH_CAPABILITIES = ("pi_runtime", "auto_publish", "exec_permission_regex")AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX = "__posthog_agent_preflight_capability="AGENT_SERVER_PREFLIGHT_REUSE_MARKER = "__posthog_agent_preflight_reuse=1"-AGENT_SERVER_PREFLIGHT_SKILLS_EXIT_CODE = 90AGENT_SERVER_PREFLIGHT_CHMOD_EXIT_CODE = 91AGENT_SERVER_PREFLIGHT_CREDENTIAL_EXIT_CODE = 92AGENT_SERVER_PREFLIGHT_TIMEOUT_SECONDS = 60@@ -223,12 +222,9 @@ def build_agent_server_preflight_script(*, probe_health: bool, executable_paths: tuple[str, ...], probe_memory_watchdog: bool = False) -> str:lines = [- f"if ! ( {build_bundled_skills_clear_command()} ); then exit {AGENT_SERVER_PREFLIGHT_SKILLS_EXIT_CODE}; fi"- ]- lines.extend(f"if ! chmod +x {shlex.quote(path)}; then exit {AGENT_SERVER_PREFLIGHT_CHMOD_EXIT_CODE}; fi"for path in executable_paths- )+ ]if probe_memory_watchdog:lines.append(build_memory_watchdog_probe_command())lines.extend(@@ -290,8 +286,8 @@ class AgentServerLaunchMixin(SandboxBase):def supports_combined_agent_server_start_and_health(self) -> bool:return True- def _write_required_file(self, path: str, payload: bytes) -> None:- result = self.write_file(path, payload)+ def _write_required_file(self, path: str, payload: bytes, *, timeout_seconds: int | None = None) -> None:+ result = self.write_file(path, payload, timeout_seconds=timeout_seconds)if result.exit_code != 0:write_stage = (result.error or "unknown")[:100]raise SandboxExecutionError(@@ -392,6 +388,7 @@ class AgentServerLaunchMixin(SandboxBase):f"{create_pr_flag}{auto_publish_flag}{branch_flag}{mcp_servers_arg}{relay_mcp_servers_arg}"f"{domains_flag}{repo_ready_flag}{exec_permission_flag}{subscription_flag}")+ server_cmd = self._wrap_agent_server_command(server_cmd)launch_started_at = "export POSTHOG_AGENT_LAUNCH_STARTED_AT_MS=$(date +%s%3N)"if repo_ready_file:@@ -420,6 +417,9 @@ class AgentServerLaunchMixin(SandboxBase):f"(nohup {server_cmd} > /tmp/agent-server.log 2>&1 & echo $! > /tmp/agent-server.pid)")+ def _wrap_agent_server_command(self, command: str) -> str:+ return command+def _sandbox_runtime(self) -> str | None:return None@@ -563,6 +563,11 @@ class AgentServerLaunchMixin(SandboxBase):def _agent_server_preflight(self, allowed_domains: list[str] | None) -> AgentServerPreflight:executable_paths = self._install_agent_server_launch_files()+ result = self.execute_in_task_filesystem(+ build_bundled_skills_clear_command(), timeout_seconds=AGENT_SERVER_PREFLIGHT_TIMEOUT_SECONDS+ )+ if result.exit_code != 0:+ raise RuntimeError(f"Failed to clear bundled skills in sandbox {self.id}: {result.stderr}")result = self.execute(build_agent_server_preflight_script(probe_health=self._agent_server_reuse_enabled(),@@ -571,8 +576,6 @@ class AgentServerLaunchMixin(SandboxBase):),timeout_seconds=AGENT_SERVER_PREFLIGHT_TIMEOUT_SECONDS,)- if result.exit_code == AGENT_SERVER_PREFLIGHT_SKILLS_EXIT_CODE:- raise RuntimeError(f"Failed to clear bundled skills in sandbox {self.id}: {result.stderr}")if result.exit_code == AGENT_SERVER_PREFLIGHT_CHMOD_EXIT_CODE:raise SandboxExecutionError("Failed to set permissions on required sandbox file",diff --git a/products/tasks/backend/logic/services/dev_stack_image.py b/products/tasks/backend/logic/services/dev_stack_image.pyindex 455087fe66c9..9007a6570ab2 100644--- a/products/tasks/backend/logic/services/dev_stack_image.py+++ b/products/tasks/backend/logic/services/dev_stack_image.py@@ -38,6 +38,7 @@ from products.tasks.backend.feature_flags import is_dev_stack_image_bake_enabledfrom products.tasks.backend.logic.services.dev_stack_image_refresh import reconcile_dev_stack_imagefrom products.tasks.backend.logic.services.dev_stack_image_state import DevStackImageStatefrom products.tasks.backend.logic.services.sandbox import SandboxConfig, SandboxTemplate, get_sandbox_class+from products.tasks.backend.logic.services.task_filesystem import TASK_FILESYSTEM_SCRIPT, read_task_filesystem_scriptfrom products.tasks.backend.metrics import observe_dev_stack_image_bakefrom products.tasks.backend.redis import get_tasks_cache@@ -209,6 +210,9 @@ def bake_dev_stack_image())try:+ result = sandbox.write_file(TASK_FILESYSTEM_SCRIPT, read_task_filesystem_script())+ if result.exit_code != 0:+ raise DevStackImageBakeError("Failed to install task filesystem image preparation")sandbox.write_file(BAKE_SCRIPT_SANDBOX_PATH, script.encode())log_tail: deque[bytes] = deque()diff --git a/products/tasks/backend/logic/services/modal_launch_preparation.py b/products/tasks/backend/logic/services/modal_launch_preparation.pyindex 1a034ecfdcde..51b1495b123f 100644--- a/products/tasks/backend/logic/services/modal_launch_preparation.py+++ b/products/tasks/backend/logic/services/modal_launch_preparation.py@@ -15,12 +15,14 @@ from .agentsh import (generate_policy_yaml,read_gh_guard_script,)+from .task_filesystem import TASK_FILESYSTEM_SCRIPT, read_task_filesystem_scriptdef build_modal_launch_preparation_script(allowed_domains: list[str] | None) -> str:files = [(BASH_ENV_SCRIPT, generate_bash_env_script().encode(), "644"),(GH_GUARD_INSTALL_PATH, read_gh_guard_script(), "755"),+ (TASK_FILESYSTEM_SCRIPT, read_task_filesystem_script(), "644"),]if allowed_domains is not None:files.extend(@@ -34,6 +36,7 @@ def build_modal_launch_preparation_script(allowed_domains: list[str] | None) ->script = ["#!/bin/bash","set -euo pipefail",+ "export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","umask 077","stage=install","staged_files=()",@@ -91,7 +94,7 @@ def build_modal_launch_preparation_script(allowed_domains: list[str] | None) ->"if pgrep -f '[a]gentsh server' > /dev/null; then exit 1; fi","mkdir -p /var/log/agentsh /var/lib/agentsh/sessions",f"rm -f -- {shlex.quote(SESSION_ID_FILE)}",- "nohup agentsh server --config /etc/agentsh/config.yaml > /var/log/agentsh/agentsh.log 2>&1 &",+ f"nohup /usr/bin/python3 -I {TASK_FILESYSTEM_SCRIPT} enter -- /usr/bin/agentsh server --config /etc/agentsh/config.yaml > /var/log/agentsh/agentsh.log 2>&1 &","daemon_pid=$!","healthy=0","for i in $(seq 1 30); do",@@ -103,7 +106,7 @@ def build_modal_launch_preparation_script(allowed_domains: list[str] | None) ->"done",'[ "$healthy" -eq 1 ]','kill -0 "$daemon_pid"',- f"session_id=$(timeout 60s agentsh session create --workspace {shlex.quote(DEFAULT_SANDBOX_WORKING_DIR)} --policy default --json | jq -er '.id | select(type == \"string\" and length > 0)')",+ f"session_id=$(timeout 60s /usr/bin/agentsh session create --workspace {shlex.quote(DEFAULT_SANDBOX_WORKING_DIR)} --policy default --json | jq -er '.id | select(type == \"string\" and length > 0)')",f"temporary=$(mktemp {shlex.quote(SESSION_ID_FILE + '.tmp.XXXXXX')})",'staged_files+=("$temporary")','printf %s "$session_id" > "$temporary"',diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex 4e623ea39a56..a2d86a238fb2 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -91,6 +91,12 @@ from products.tasks.backend.logic.services.modal_provision_diagnostics import (summarize_modal_output,)from products.tasks.backend.logic.services.sandbox import redact_sandbox_command+from products.tasks.backend.logic.services.task_filesystem import (+ TASK_FILESYSTEM_SCRIPT,+ TASK_FILESYSTEM_VERSION,+ read_task_filesystem_script,+ task_filesystem_command,+)from products.tasks.backend.models import DevStackImageTarget, SandboxSnapshotfrom .agent_server_launcher import (@@ -753,6 +759,8 @@ def _prepare_local_modal_build_context(template: SandboxTemplate) -> tuple[str,shutil.copy2(base_dir / LOCAL_MODAL_MEMORY_WATCHDOG, context_dir / LOCAL_MODAL_MEMORY_WATCHDOG)if template == SandboxTemplate.DEFAULT_BASE:+ filesystem_script = Path("products/tasks/backend/sandbox/images/task_filesystem.py")+ shutil.copy2(base_dir / filesystem_script, context_dir / filesystem_script)destination_hogli_shim_path = context_dir / LOCAL_MODAL_HOGLI_SHIM_SCRIPTdestination_hogli_shim_path.parent.mkdir(parents=True, exist_ok=True)shutil.copy2(base_dir / LOCAL_MODAL_HOGLI_SHIM_SCRIPT, destination_hogli_shim_path)@@ -824,6 +832,36 @@ class ModalSandbox(AgentServerLaunchMixin):def _install_agent_server_launch_files(self) -> tuple[str, ...]:return ()+ def _wrap_agent_server_command(self, command: str) -> str:+ return f"/usr/bin/python3 -I {TASK_FILESYSTEM_SCRIPT} enter -- {command}"++ def _prepare_task_filesystem(self) -> None:+ if self.config.template not in {+ SandboxTemplate.DEFAULT_BASE,+ SandboxTemplate.AUTORESEARCH_BASE,+ SandboxTemplate.VM_BASE,+ }:+ return+ if (self.config.metadata or {}).get("purpose") == "dev_stack_image_bake":+ return+ enabled = settings.TASKS_SANDBOX_PERSISTENT_FILESYSTEM_ENABLED+ if self.config.snapshot_restored:+ result = self.execute(f"test -f {TASK_FILESYSTEM_VERSION} && printf 1", timeout_seconds=30)+ enabled = result.exit_code == 0 and result.stdout == "1"+ elif enabled:+ result = self.execute(+ "test -d /opt/posthog/task-home && test ! -L /opt/posthog/task-home && printf 1", timeout_seconds=30+ )+ enabled = result.exit_code == 0 and result.stdout == "1"+ if not enabled:+ return+ self._write_required_file(TASK_FILESYSTEM_SCRIPT, read_task_filesystem_script())+ result = self.execute(+ f"/usr/bin/python3 -I {TASK_FILESYSTEM_SCRIPT} initialize {self._sandbox_runtime()}", timeout_seconds=120+ )+ if result.exit_code != 0:+ raise RuntimeError(f"Task filesystem initialization failed: {result.stderr[-2000:]}")+def _sandbox_runtime(self) -> str | None:return "vm" if self.config.is_vm else "gvisor"@@ -1181,6 +1219,24 @@ class ModalSandbox(AgentServerLaunchMixin):sb.set_tags(config.metadata)sandbox = cls(sandbox=sb, config=config)+ try:+ sandbox._prepare_task_filesystem()+ except Exception as e:+ try:+ cls._terminate_unready_sandbox(sb, config)+ except SandboxProvisionError:+ logger.exception(+ "Failed to terminate sandbox after task filesystem initialization",+ extra={"sandbox_id": sb.object_id},+ )+ if isinstance(e, SandboxControlPlaneError):+ sb = None+ raise+ raise SandboxProvisionError(+ "Task filesystem initialization failed",+ {"config_name": config.name, "sandbox_id": sb.object_id},+ cause=e,+ ) from eif modal_output is not None:sandbox.provision_diagnostics = summarize_modal_output(modal_output.getvalue())@@ -1417,6 +1473,12 @@ class ModalSandbox(AgentServerLaunchMixin):cause=RuntimeError(redacted_error),)+ def execute_in_task_filesystem(self, command: str, timeout_seconds: int | None = None) -> ExecutionResult:+ self._write_required_file(+ TASK_FILESYSTEM_SCRIPT, read_task_filesystem_script(), timeout_seconds=timeout_seconds+ )+ return self.execute(task_filesystem_command(command), timeout_seconds=timeout_seconds)+def execute(self,command: str,diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 4d10f52960e5..8a9cb276459f 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -443,7 +443,10 @@ def build_bundled_skills_clear_command() -> str:vars, but the container environment still holds the value the launcher set."""paths = " ".join(shlex.quote(path) for path in BUNDLED_SKILLS_PATHS)- return f'if [ "${ENV_DISABLE_BUNDLED_SKILLS}" = "1" ]; then rm -rf {paths} && mkdir -p {paths}; fi'+ return (+ "export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin; "+ f'if [ "${ENV_DISABLE_BUNDLED_SKILLS}" = "1" ]; then /usr/bin/rm -rf {paths} && /usr/bin/mkdir -p {paths}; fi'+ )def build_agent_server_capability_probe(capability: str) -> str:@@ -492,6 +495,9 @@ class SandboxBase(ABC):@abstractmethoddef execute(self, command: str, timeout_seconds: int | None = None) -> ExecutionResult: ...+ def execute_in_task_filesystem(self, command: str, timeout_seconds: int | None = None) -> ExecutionResult:+ return self.execute(command, timeout_seconds=timeout_seconds)+@abstractmethoddef execute_stream(self, command: str, timeout_seconds: int | None = None) -> ExecutionStream: ...@@ -560,9 +566,11 @@ class SandboxBase(ABC):# POSTHOG_PERSONAL_API_KEY / GITHUB_TOKEN. `env -i` drops those credentials and the# user PATH; the fixed PATH resolves only real system binaries (start-dockerd lives# in /usr/local/bin). HOME=/root covers tooling that needs it (dockerd runs as root).- result = self.execute(+ result = self.execute_in_task_filesystem("[ -x /usr/local/bin/bootstrap-dev-stack ] || exit 3; "- "/usr/bin/env -i HOME=/root PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin "+ "docker_config=$(/usr/bin/mktemp -d /run/posthog-bootstrap-docker.XXXXXX) || exit 1; "+ '/usr/bin/env -i HOME=/root DOCKER_CONFIG="$docker_config" '+ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin ""setsid /usr/local/bin/bootstrap-dev-stack >/var/log/bootstrap-dev-stack.log 2>&1 </dev/null &",timeout_seconds=30,)@@ -948,7 +956,7 @@ def build_health_check_command(f"SECONDS=0; i=0; max_attempts={max_attempts}; budget={budget_seconds}; while :; do "" i=$((i + 1)); "f"{process_check}"- f" body=$(curl -s --max-time {HEALTH_CURL_MAX_TIME_SECONDS} http://localhost:{port}/health); "+ f" body=$(curl -q -s --max-time {HEALTH_CURL_MAX_TIME_SECONDS} http://localhost:{port}/health); "" status=$?; "' if [ "$status" = "0" ]; then '' case "$body" in *claude_credential_unavailable*) echo "claude_credential_unavailable"; exit 1;; 'diff --git a/products/tasks/backend/logic/services/task_filesystem.py b/products/tasks/backend/logic/services/task_filesystem.pynew file mode 100644index 000000000000..fbaf42d9a047--- /dev/null+++ b/products/tasks/backend/logic/services/task_filesystem.py@@ -0,0 +1,14 @@+import shlex+from pathlib import Path++TASK_FILESYSTEM_SCRIPT = "/opt/posthog/task-filesystem.py"+TASK_FILESYSTEM_VERSION = "/tmp/workspace/.posthog/task-filesystem/version"+TASK_FILESYSTEM_LOCAL_SCRIPT = Path(__file__).resolve().parents[2] / "sandbox/images/task_filesystem.py"+++def read_task_filesystem_script() -> bytes:+ return TASK_FILESYSTEM_LOCAL_SCRIPT.read_bytes()+++def task_filesystem_command(command: str) -> str:+ return f"/usr/bin/python3 -I {TASK_FILESYSTEM_SCRIPT} enter -- /bin/bash -c {shlex.quote(command)}"diff --git a/products/tasks/backend/logic/services/test_modal_sandbox.py b/products/tasks/backend/logic/services/test_modal_sandbox.pyindex 53aeb7150527..998c47e25443 100644--- a/products/tasks/backend/logic/services/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/test_modal_sandbox.py@@ -98,7 +98,8 @@ class TestModalSandboxWriteFile:assert "rm -f /tmp/credentials.tmp-*" in commandassert " && mv /tmp/credentials.tmp-" in command- def test_uses_bounded_exec_path_when_timeout_is_set(self, mocker):+ @pytest.mark.parametrize("task_filesystem", [False, True])+ def test_uses_bounded_exec_path_when_timeout_is_set(self, mocker, task_filesystem: bool) -> None:handle = MagicMock(object_id="sb-test")handle.poll.return_value = Nonemocker.patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock())@@ -106,16 +107,16 @@ class TestModalSandboxWriteFile:execute = mocker.patch.object(sandbox,"execute",- side_effect=[- ExecutionResult(stdout="", stderr="", exit_code=0),- ExecutionResult(stdout="", stderr="", exit_code=0),- ],+ return_value=ExecutionResult(stdout="", stderr="", exit_code=0),)- sandbox.write_file("/tmp/credentials", b"token=value\x00", timeout_seconds=15)+ if task_filesystem:+ sandbox.execute_in_task_filesystem("echo ready", timeout_seconds=30)+ else:+ sandbox.write_file("/tmp/credentials", b"token=value\x00", timeout_seconds=30)handle.filesystem.write_bytes.assert_not_called()- assert all(call.kwargs["timeout_seconds"] == 15 for call in execute.call_args_list)+ assert all(call.kwargs["timeout_seconds"] == 30 for call in execute.call_args_list)def test_chunks_large_exec_fallback_payloads(self, mocker):handle = MagicMock(object_id="sb-test")@@ -179,6 +180,10 @@ class TestModalSandboxWriteFile:def patched_modal(mocker):fake_sandbox = MagicMock()fake_sandbox.object_id = "sb-test"+ fake_sandbox.poll.return_value = None+ fake_sandbox.exec.return_value.stdout.read.return_value = ""+ fake_sandbox.exec.return_value.stderr.read.return_value = ""+ fake_sandbox.exec.return_value.returncode = 0mocker.patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock())mocker.patch(@@ -402,6 +407,7 @@ class TestLocalModalBuildContext:assert (root / LOCAL_MODAL_AGENT_SHADOW_DIR / "go.mod").is_file()assert (root / LOCAL_MODAL_AGENT_SHADOW_DIR / "main.go").is_file()assert (root / LOCAL_MODAL_HOGLI_SHIM_SCRIPT).is_file()+ assert (root / "products/tasks/backend/sandbox/images/task_filesystem.py").is_file()finally:shutil.rmtree(context_dir, ignore_errors=True)_prepare_local_modal_build_context.cache_clear()diff --git a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py b/products/tasks/backend/logic/services/tests/test_docker_sandbox.pyindex 35dc13acfc1a..cc3172a0b894 100644--- a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py@@ -200,7 +200,7 @@ def test_start_agent_server_stages_the_codex_run_token_again_for_the_branchless_repository=None, task_id="t1", run_id="r1", branch="feature", codex_run_token="run-token")- token_writes = [call for call in write_file.call_args_list if call.args[0] == "/tmp/agent-codex-run-token"]+ token_writes = [call for call in write_file.call_args_list if call.args[0] == "/run/posthog/agent-codex-run-token"]assert len(token_writes) == 2@@ -212,7 +212,7 @@ def test_start_agent_server_launch_failure_is_captured(_name: str, capabilities:def execute(command: str, **kwargs) -> ExecutionResult:# Only the launch fails; the bundled-skills clear and the launch prep that precede it succeed.- if ENV_DISABLE_BUNDLED_SKILLS in command:+ if ENV_DISABLE_BUNDLED_SKILLS in command or AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX in command:return _preflight_result(capabilities)if command.startswith("chmod "):return _ok_result()diff --git a/products/tasks/backend/logic/services/tests/test_modal_launch_preparation.py b/products/tasks/backend/logic/services/tests/test_modal_launch_preparation.pyindex 8eae5132d9e7..b9796c5f5c5b 100644--- a/products/tasks/backend/logic/services/tests/test_modal_launch_preparation.py+++ b/products/tasks/backend/logic/services/tests/test_modal_launch_preparation.py@@ -28,7 +28,11 @@ from products.tasks.backend.logic.services.launch_preparation_metrics import ()from products.tasks.backend.logic.services.modal_launch_preparation import build_modal_launch_preparation_scriptfrom products.tasks.backend.logic.services.modal_sandbox import ModalSandbox-from products.tasks.backend.logic.services.sandbox import ExecutionResult, SandboxConfig+from products.tasks.backend.logic.services.sandbox import (+ ExecutionResult,+ SandboxConfig,+ build_bundled_skills_clear_command,+)@pytest.fixture@@ -55,7 +59,13 @@ esacpath = bin_dir / namepath.write_text(f"#!/bin/bash\n{command}\n")path.chmod(0o755)- return {"PATH": f"{bin_dir}:{os.environ['PATH']}"}+ untrusted_bin = tmp_path / "untrusted"+ untrusted_bin.mkdir()+ for name in ("agentsh", "mkdir", "rm"):+ path = untrusted_bin / name+ path.write_text(f"#!/bin/bash\ntouch {shlex.quote(str(tmp_path / 'untrusted-executed'))}\nexit 99\n")+ path.chmod(0o755)+ return {"PATH": f"{untrusted_bin}:{os.environ['PATH']}"}def run_preparation(@@ -63,6 +73,11 @@ def run_preparation() -> subprocess.CompletedProcess[str]:script = build_modal_launch_preparation_script(allowed_domains)script = re.sub(r"/(?:tmp|etc|opt|var)/", lambda match: f"{root}{match.group()}", script)+ script = script.replace(+ "export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",+ f"export PATH={shlex.quote(str(root / 'bin'))}:/usr/bin:/bin",+ )+ script = script.replace("/usr/bin/agentsh", str(root / "bin/agentsh"))if environment.get("PREPARATION_REAL_DAEMON") != "1":script = 'kill() { [ "${PREPARATION_FAULT:-}" != daemon_start ]; }\n' + scriptscript_path = root / "preparation.sh"@@ -90,6 +105,18 @@ def test_preparation_installs_complete_files_and_can_be_reapplied(})for _ in range(2):+ clear = re.sub(+ r"/(?:root|scripts)/", lambda match: f"{tmp_path}{match.group()}", build_bundled_skills_clear_command()+ )+ result = subprocess.run(+ ["bash", "-c", clear],+ env={**shell_environment, "POSTHOG_CODE_DISABLE_BUNDLED_SKILLS": "1"},+ capture_output=True,+ text=True,+ timeout=10,+ )+ assert result.returncode == 0, result.stderr+ assert not (tmp_path / "untrusted-executed").exists()result = run_preparation(tmp_path, allowed_domains, shell_environment)assert result.returncode == 0, result.stderrfor path, (payload, mode) in expected_files.items():@@ -99,6 +126,7 @@ def test_preparation_installs_complete_files_and_can_be_reapplied(assert not list(tmp_path.rglob("*.tmp.*"))assert not (tmp_path / "preparation.sh").exists()assert not (tmp_path / "injected").exists()+ assert not (tmp_path / "untrusted-executed").exists()if allowed_domains is None:assert not (tmp_path / "etc/agentsh").exists()assert not (tmp_path / SESSION_ID_FILE.lstrip("/")).exists()@@ -198,6 +226,11 @@ def test_failed_preparation_never_launches_agent_server(failure: str, log_availawith (patch.object(sandbox, "execute", side_effect=execute) as remote_execute,+ patch.object(+ sandbox,+ "_agent_server_preflight",+ return_value=AgentServerPreflight(reused=False, capabilities=frozenset()),+ ),patch.object(sandbox,"write_file",diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.pyindex feb7ff86ee4c..56951fd878ea 100644--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py@@ -498,6 +498,59 @@ class TestModalSandboxAgentServer:with patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock()):return ModalSandbox(sandbox=mock_modal_sandbox, config=config)+ @pytest.mark.parametrize(+ "template,purpose",+ [(SandboxTemplate.STREAMLIT_BASE, ""), (SandboxTemplate.DEFAULT_BASE, "dev_stack_image_bake")],+ )+ @override_settings(TASKS_SANDBOX_PERSISTENT_FILESYSTEM_ENABLED=True)+ def test_non_task_template_does_not_initialize_task_filesystem(+ self, mock_sandbox: Any, template: SandboxTemplate, purpose: str+ ) -> None:+ mock_sandbox.config.template = template+ mock_sandbox.config.metadata = {"purpose": purpose}+ with patch.object(mock_sandbox, "execute") as execute, patch.object(mock_sandbox, "write_file") as write:+ mock_sandbox._prepare_task_filesystem()+ execute.assert_not_called()+ write.assert_not_called()++ @pytest.mark.parametrize(+ "enabled,snapshot_kind,compatible",+ [+ (False, "directory", True),+ (False, "filesystem", True),+ (True, "filesystem", True),+ (True, "filesystem", False),+ (True, "directory", False),+ (True, None, True),+ (True, None, False),+ (False, None, True),+ ],+ )+ def test_initializes_only_compatible_task_filesystems(+ self, mock_sandbox: Any, enabled: bool, snapshot_kind: str | None, compatible: bool+ ) -> None:+ mock_sandbox.config.snapshot_restored = snapshot_kind is not None+ mock_sandbox.config.snapshot_kind = snapshot_kind+ with (+ override_settings(TASKS_SANDBOX_PERSISTENT_FILESYSTEM_ENABLED=enabled),+ patch.object(+ mock_sandbox,+ "execute",+ return_value=ExecutionResult(+ stdout="1" if compatible else "", stderr="", exit_code=0 if compatible else 1+ ),+ ) as execute,+ patch.object(mock_sandbox, "_write_required_file") as write,+ ):+ mock_sandbox._prepare_task_filesystem()+ initialize = compatible and (snapshot_kind is not None or enabled)+ assert write.call_count == int(initialize)+ if snapshot_kind is not None or enabled:+ assert ("initialize gvisor" in execute.call_args.args[0]) == initialize+ assert ("test -f" if snapshot_kind else "test -d") in execute.call_args_list[0].args[0]+ else:+ execute.assert_not_called()+def test_get_connect_credentials_success(self, mock_sandbox: Any):result = mock_sandbox.get_connect_credentials()@@ -690,7 +743,7 @@ class TestModalSandboxAgentServer:command = _agent_server_launch_command(mock_sandbox.execute)barrier = command.index("while [ ! -f /tmp/workspace/.repo-ready ]; do sleep 0.1; done")marker = command.index("export POSTHOG_AGENT_LAUNCH_STARTED_AT_MS=$(date +%s%3N)")- process = command.index("exec env", marker)+ process = command.index("exec /usr/bin/python3 -I /opt/posthog/task-filesystem.py enter -- env", marker)assert barrier < marker < processassert "--repoReadyFile /tmp/workspace/.repo-ready" in command@@ -975,7 +1028,7 @@ class TestModalSandboxAgentServer:)def execute(command: str, timeout_seconds: int | None = None) -> ExecutionResult:- if ENV_DISABLE_BUNDLED_SKILLS in command:+ if ENV_DISABLE_BUNDLED_SKILLS in command or _is_preflight_command(command):return ExecutionResult(stdout="", stderr="", exit_code=0, error=None)return ExecutionResult(stdout="", stderr="npx: command not found", exit_code=127, error=None)@@ -1051,10 +1104,13 @@ class TestModalSandboxAgentServer:mock_free.assert_not_called()commands = [call.args[0] for call in mock_sandbox.execute.call_args_list]# Bundled-skills clear, then refreshed bash-env and gh-guard files before reuse is accepted.- assert ENV_DISABLE_BUNDLED_SKILLS in commands[0]- assert any("mv" in command and "/tmp/agentsh-bash-env.sh" in command for command in commands[1:])- assert any("mv" in command and "/opt/posthog/bin/gh" in command for command in commands[1:])- assert any(command == "chmod +x /opt/posthog/bin/gh" for command in commands[1:])+ preflight_index = next(index for index, command in enumerate(commands) if _is_preflight_command(command))+ assert "task-filesystem.py enter" not in commands[preflight_index]+ assert "task-filesystem.py enter" in commands[preflight_index - 1]+ after_preflight = commands[preflight_index + 1 :]+ assert any("mv" in command and "/tmp/agentsh-bash-env.sh" in command for command in after_preflight)+ assert any("mv" in command and "/opt/posthog/bin/gh" in command for command in after_preflight)+ assert any(command == "chmod +x /opt/posthog/bin/gh" for command in after_preflight)def test_start_agent_server_relaunches_when_agentsh_is_unhealthy(self, mock_sandbox: Any):def execute(command: str, timeout_seconds: int | None = None) -> ExecutionResult:@@ -1149,7 +1205,7 @@ class TestModalSandboxAgentServer:assert "nohup" in commandassert "http://localhost:8080/health" in command- def test_start_agent_server_runs_one_preflight_exec_before_the_launch(self, mock_sandbox: Any):+ def test_start_agent_server_separates_task_cleanup_from_provider_preflight(self, mock_sandbox: Any):mock_sandbox.execute = MagicMock(return_value=ExecutionResult(stdout=_preflight_stdout(), stderr="", exit_code=0, error=None))@@ -1164,9 +1220,12 @@ class TestModalSandboxAgentServer:commands = [call.args[0] for call in mock_sandbox.execute.call_args_list]launch_index = commands.index(_agent_server_launch_command(mock_sandbox.execute))- assert launch_index == 2- assert _is_preflight_command(commands[0])- assert commands[1].startswith("bash /tmp/posthog-launch-preparation-")+ assert launch_index == 3+ assert "task-filesystem.py enter" in commands[0]+ assert "curl" not in commands[0]+ assert _is_preflight_command(commands[1])+ assert "task-filesystem.py enter" not in commands[1]+ assert commands[2].startswith("bash /tmp/posthog-launch-preparation-")def test_create_snapshot_waits_for_container_before_snapshot(self, mock_sandbox: Any) -> None:events: list[str] = []@@ -1913,9 +1972,10 @@ class TestModalSandboxCreateImageFallback:bare_snapshot = MagicMock(name="bare_snapshot")overlaid_snapshot = MagicMock(name="overlaid_snapshot")- sandbox, images_tried = self._create_failing_on(- config, failing_image=overlaid_snapshot, loaded_image=bare_snapshot- )+ with patch.object(ModalSandbox, "execute", return_value=ExecutionResult(stdout="", stderr="", exit_code=1)):+ sandbox, images_tried = self._create_failing_on(+ config, failing_image=overlaid_snapshot, loaded_image=bare_snapshot+ )assert images_tried == [overlaid_snapshot, bare_snapshot]# The run still restored from the snapshot — the downgrade only cost the overlay.@@ -2203,14 +2263,36 @@ class TestModalSandboxCreateImageFallback:mock_sb.terminate.assert_called_once()assert error.value.non_retryable is False- def test_unready_sandbox_that_refuses_to_terminate_fails_the_provision(self):+ @pytest.mark.parametrize(+ "failure,termination_recovers",+ [+ ("readiness", False),+ ("filesystem", False),+ ("filesystem", True),+ ("rate_limit", False),+ ("rate_limit", True),+ ],+ )+ def test_unready_sandbox_retries_termination_before_failing_provision(+ self, failure: str, termination_recovers: bool+ ) -> None:# process-task only records a sandbox id once create() has returned, so an unready# sandbox we could not terminate is invisible to every later cleanup path. Failing# beats recovering onto the next image and leaving the old one billing.mock_sb = MagicMock()mock_sb.object_id = "sb-stuck"- mock_sb.wait_until_ready.side_effect = ModalTimeoutError("readiness probe timed out")- mock_sb.terminate.side_effect = ModalServiceError("terminate failed")+ if failure == "readiness":+ mock_sb.wait_until_ready.side_effect = ModalTimeoutError("readiness probe timed out")+ mock_sb.terminate.side_effect = (+ [ModalServiceError("terminate failed"), None]+ if termination_recovers+ else ModalServiceError("terminate failed")+ )+ initialization_error = (+ SandboxRateLimitedError("rate limited", {"sandbox_id": "sb-stuck"})+ if failure == "rate_limit"+ else RuntimeError("filesystem setup failed")+ )with (patch("products.tasks.backend.logic.services.modal_sandbox.modal.enable_output"),@@ -2226,15 +2308,23 @@ class TestModalSandboxCreateImageFallback:),patch("products.tasks.backend.logic.services.modal_sandbox.modal.Sandbox.create", return_value=mock_sb),patch("products.tasks.backend.logic.services.modal_sandbox.time.sleep"),+ patch.object(ModalSandbox, "_prepare_task_filesystem", side_effect=initialization_error),patch("products.tasks.backend.exceptions.capture_exception"),):- with pytest.raises(SandboxProvisionError) as error:+ with pytest.raises(SandboxRateLimitedError if failure == "rate_limit" else SandboxProvisionError) as error:ModalSandbox.create(SandboxConfig(name="t", template=SandboxTemplate.VM_BASE, custom_image_name="posthog-dev-stack"))- assert mock_sb.terminate.call_count == UNREADY_TERMINATE_MAX_ATTEMPTS- assert "Failed to terminate an unready sandbox" in str(error.value)+ assert mock_sb.terminate.call_count == (2 if termination_recovers else UNREADY_TERMINATE_MAX_ATTEMPTS)+ assert error.value.context["sandbox_id"] == "sb-stuck"+ if failure == "rate_limit":+ assert error.value is initialization_error+ assert error.value.next_retry_delay is not None+ elif failure == "filesystem":+ assert error.value.__cause__ is initialization_error+ else:+ assert "Failed to terminate an unready sandbox" in str(error.value)def test_create_failure_inside_the_recovery_stays_on_the_fallback_chain(self):# The recovery re-enters the image chain, which records its own downgrade on@@ -2440,7 +2530,10 @@ class TestLaunchDevStackBootstrap:sandbox = self._sandbox()result = ExecutionResult(stdout="", stderr="", exit_code=exit_code, error=None)- with patch.object(ModalSandbox, "execute", return_value=result) as mock_execute:+ with (+ patch.object(ModalSandbox, "execute", return_value=result) as mock_execute,+ patch.object(ModalSandbox, "_write_required_file"),+ ):assert sandbox.launch_dev_stack_bootstrap() is expected# Absolute path, not a PATH probe — PATH could be shadowed inside the image.@@ -2495,7 +2588,10 @@ class TestLaunchDevStackBootstrap:sandbox = self._sandbox(snapshot_restored=True, snapshot_kind=SNAPSHOT_KIND_DIRECTORY)result = ExecutionResult(stdout="", stderr="", exit_code=0, error=None)- with patch.object(ModalSandbox, "execute", return_value=result):+ with (+ patch.object(ModalSandbox, "_write_required_file"),+ patch.object(ModalSandbox, "execute", return_value=result),+ ):assert sandbox.launch_dev_stack_bootstrap() is Truedef test_launch_scrubs_environment_so_a_poisoned_workspace_path_cannot_run_with_credentials(self):@@ -2507,12 +2603,17 @@ class TestLaunchDevStackBootstrap:sandbox = self._sandbox(snapshot_restored=True, snapshot_kind=SNAPSHOT_KIND_DIRECTORY)result = ExecutionResult(stdout="", stderr="", exit_code=0, error=None)- with patch.object(ModalSandbox, "execute", return_value=result) as mock_execute:+ with (+ patch.object(ModalSandbox, "_write_required_file"),+ patch.object(ModalSandbox, "execute", return_value=result) as mock_execute,+ ):assert sandbox.launch_dev_stack_bootstrap() is Truecommand = mock_execute.call_args.args[0]assert "/usr/bin/env -i " in command # absolute launcher, empty environmentassert "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" in command+ assert 'DOCKER_CONFIG="$docker_config"' in command+ assert "/usr/bin/mktemp -d /run/posthog-bootstrap-docker." in commandassert "/tmp/workspace" not in command# env -i means no credential is ever named in (or inherited by) the helper's env.assert "TOKEN" not in command and "API_KEY" not in commanddiff --git a/products/tasks/backend/logic/services/tests/test_sandbox_health_check.py b/products/tasks/backend/logic/services/tests/test_sandbox_health_check.pyindex f50bf8883acb..a8f911ed6bc2 100644--- a/products/tasks/backend/logic/services/tests/test_sandbox_health_check.py+++ b/products/tasks/backend/logic/services/tests/test_sandbox_health_check.py@@ -1,7 +1,9 @@import osimport timeimport subprocess+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Path+from threading import Threadimport pytest@@ -25,6 +27,37 @@ def _path_with_fake_curl(tmp_path: Path, body: str, delay_seconds: float) -> dicreturn {**os.environ, "PATH": f"{tmp_path}{os.pathsep}{os.environ['PATH']}"}+def test_health_check_ignores_curl_config(tmp_path: Path) -> None:+ requests: list[str] = []++ class Handler(BaseHTTPRequestHandler):+ def do_GET(self) -> None:+ requests.append(self.path)+ self.send_response(200)+ self.end_headers()+ self.wfile.write(b'{"status":"ok","hasSession":true}')++ with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:+ port = server.server_port+ (tmp_path / ".curlrc").write_text(f'url = "http://127.0.0.1:{port}/unexpected"\n')+ thread = Thread(target=server.serve_forever)+ thread.start()+ try:+ result = subprocess.run(+ ["bash", "-c", build_health_check_command(port, 1, 0.0)],+ env={**os.environ, "CURL_HOME": str(tmp_path)},+ capture_output=True,+ text=True,+ timeout=10,+ )+ finally:+ server.shutdown()+ thread.join()++ assert result.returncode == 0, result.stderr+ assert requests == ["/health"]++@pytest.mark.parametrize(("body", "expected_exit_code", "expected_stdout"),[diff --git a/products/tasks/backend/logic/services/tests/test_task_filesystem.py b/products/tasks/backend/logic/services/tests/test_task_filesystem.pynew file mode 100644index 000000000000..7f99038883b5--- /dev/null+++ b/products/tasks/backend/logic/services/tests/test_task_filesystem.py@@ -0,0 +1,121 @@+import os+import sys+import json+import subprocess+from pathlib import Path++import pytest++from products.tasks.backend.sandbox.images import task_filesystem++[email protected]("restored", [False, True])+def test_home_seed_enters_the_workspace_only_when_activated(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, restored: bool+) -> None:+ state = tmp_path / "workspace/.posthog/task-filesystem"+ seed = tmp_path / "image/home"+ seed.mkdir(parents=True)+ (seed / "file").write_text("seed")+ state.mkdir(parents=True)+ home = state / "home"+ if restored:+ home.mkdir()+ (home / "file").write_text("saved")+ (state / "version").write_text(task_filesystem.VERSION)+ monkeypatch.setattr(task_filesystem, "STATE", state)+ monkeypatch.setattr(task_filesystem, "HOME_SEED", seed)+ monkeypatch.setattr(task_filesystem, "RUNTIME", tmp_path / "runtime")++ task_filesystem.prepare_home()++ assert (home / "file").read_text() == ("saved" if restored else "seed")+ assert seed.exists() == restored+++def test_pinned_settings_are_recreated_outside_persistent_home(tmp_path: Path, monkeypatch) -> None:+ home = tmp_path / "home"+ settings = home / ".claude/posthog-session-settings"+ settings.mkdir(parents=True)+ (settings / "old.json").write_text('{"env":{"ANTHROPIC_AUTH_TOKEN":"synthetic-token"}}')+ runtime = tmp_path / "runtime"+ monkeypatch.setattr(task_filesystem, "RUNTIME", runtime)++ task_filesystem.prepare_runtime_home(home)++ assert settings.is_symlink()+ assert not (settings / "old.json").exists()+ (settings / "new.json").write_text("fresh")+ assert (runtime / "claude-session-settings/new.json").read_text() == "fresh"+ assert (runtime / "claude-session-settings").stat().st_mode & 0o777 == 0o700+ task_filesystem.prepare_runtime_home(home)+ assert (settings / "new.json").read_text() == "fresh"+++def test_pinned_settings_reject_an_unexpected_symlink(tmp_path: Path, monkeypatch) -> None:+ home = tmp_path / "home"+ (home / ".claude").mkdir(parents=True)+ external = tmp_path / "external"+ external.mkdir()+ (home / ".claude/posthog-session-settings").symlink_to(external)+ monkeypatch.setattr(task_filesystem, "RUNTIME", tmp_path / "runtime")++ with pytest.raises(RuntimeError, match="Unexpected runtime path"):+ task_filesystem.prepare_runtime_home(home)+ assert list(external.iterdir()) == []++[email protected]("linked", ["workspace", "state", "home"])+def test_initialization_rejects_symlinked_state_before_writing(tmp_path: Path, monkeypatch, linked: str) -> None:+ workspace = tmp_path / "workspace"+ state = workspace / ".posthog/task-filesystem"+ runtime = tmp_path / "runtime"+ destination = {"workspace": workspace, "state": state, "home": state / "home"}[linked]+ target = tmp_path / "external"+ target.mkdir()+ destination.parent.mkdir(parents=True, exist_ok=True)+ destination.symlink_to(target, target_is_directory=True)+ monkeypatch.setattr(task_filesystem, "WORKSPACE", workspace)+ monkeypatch.setattr(task_filesystem, "STATE", state)+ monkeypatch.setattr(task_filesystem, "RUNTIME", runtime)++ with pytest.raises(RuntimeError, match="real directory"):+ task_filesystem.initialize("vm")++ assert list(target.iterdir()) == []++[email protected]("saved_version", [None, "1"])+def test_entry_refuses_lost_namespace_instead_of_using_provider_paths(+ tmp_path: Path, saved_version: str | None+) -> None:+ state = tmp_path / "state"+ state.mkdir()+ if saved_version is not None:+ (state / "version").write_text(saved_version)+ output = tmp_path / "executed"+ script = (+ "from pathlib import Path; "+ "from products.tasks.backend.sandbox.images import task_filesystem as fs; "+ f"fs.STATE=Path({str(state)!r}); fs.RUNTIME=Path({str(tmp_path / 'runtime')!r}); "+ f"fs.enter({[sys.executable, '-c', f'from pathlib import Path; Path({str(output)!r}).touch()']!r})"+ )++ result = subprocess.run(+ [sys.executable, "-c", script],+ cwd=Path(__file__).resolve().parents[6],+ capture_output=True,+ text=True,+ timeout=10,+ )++ assert (result.returncode == 0) == (saved_version is None), result.stderr+ assert output.exists() == (saved_version is None)+++def test_entry_rejects_reused_namespace_holder_pid(tmp_path: Path, monkeypatch) -> None:+ (tmp_path / "ready").write_text(json.dumps({"pid": os.getpid(), "namespace": "mnt:[1]"}))+ monkeypatch.setattr(task_filesystem, "RUNTIME", tmp_path)++ with pytest.raises(RuntimeError, match="no longer available"):+ task_filesystem.enter(["/bin/true"])diff --git a/products/tasks/backend/prompts.py b/products/tasks/backend/prompts.pyindex 900d894b19ac..0eb1ff52ef92 100644--- a/products/tasks/backend/prompts.py+++ b/products/tasks/backend/prompts.py@@ -29,7 +29,7 @@ dependencies, a `posthog-setup-report.md` summary. It'll also possibly contain a`.posthog-events.json` plan and some skills definitions under a harness skills folder such as`.claude/skills/*` or `.agents/skills/*`.-The wizard's full console output is saved to `/tmp/wizard-cloud-run/wizard-output.log` (outside the+The wizard's full console output is saved to `/tmp/workspace/.posthog/wizard-cloud-run/wizard-output.log` (outside therepository, so it can never be committed). Read it whenever you need to understand what the wizardactually did - which files it touched, any warnings it printed, or why something in the working treelooks the way it does.diff --git a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-baseindex 1156b0c6c7f0..08385e5f3b68 100644--- a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base+++ b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base@@ -223,4 +223,7 @@ RUN python3 --version && \fi && \/scripts/node_modules/.bin/agent-server --help >/dev/null+COPY products/tasks/backend/sandbox/images/task_filesystem.py /opt/posthog/task-filesystem.py+RUN /usr/bin/python3 -I /opt/posthog/task-filesystem.py seed-home+CMD ["/bin/bash"]diff --git a/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh b/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.shindex 2a2b8bd435f2..49558d77af66 100644--- a/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh+++ b/products/tasks/backend/sandbox/images/bake-posthog-dev-stack.sh@@ -347,6 +347,8 @@ echo "dev stack ready — from the posthog checkout: uv sync && source .venv/binEOFchmod +x /usr/local/bin/bootstrap-dev-stack+/usr/bin/python3 -I /opt/posthog/task-filesystem.py seed-home+mkdir -p "$(dirname "$BAKE_MANIFEST")"BAKED_AGENT_VERSION=$(node -p "require('/scripts/node_modules/@posthog/agent/package.json').version")export BAKED_SHA BAKE_MANIFEST BAKED_AGENT_VERSIONdiff --git a/products/tasks/backend/sandbox/images/task_filesystem.py b/products/tasks/backend/sandbox/images/task_filesystem.pynew file mode 100644index 000000000000..4f20235cac3e--- /dev/null+++ b/products/tasks/backend/sandbox/images/task_filesystem.py@@ -0,0 +1,232 @@+import os+import sys+import json+import time+import fcntl+import shutil+import signal+import argparse+import tempfile+import subprocess+from pathlib import Path++WORKSPACE = Path("/tmp/workspace")+STATE = WORKSPACE / ".posthog/task-filesystem"+HOME_SEED = Path("/opt/posthog/task-home")+RUNTIME = Path("/run/posthog/task-filesystem")+VERSION = "1"+RUNTIME_TMP_PATHS = (+ "agent-env",+ "agent-github-env",+ "agent-oauth-env",+ "agentsh-bash-env.sh",+ "agentsh-env-wrapper.sh",+ "agentsh-session-id",+ "agent-server.pid",+ "agent-server.log",+ "agent-cli.pid",+ "posthog-memory-watchdog.json",+ "posthog-memory-watchdog.jsonl",+ "posthog-memory-watchdog.log",+ "posthog-preview",+ "start-dev-stack-preview.sh",+ "posthog-desktop-bootstrap",+)+++def require_directory(path: Path) -> None:+ if path.resolve() != path:+ raise RuntimeError(f"Task filesystem path must be a real directory: {path}")+ path.mkdir(parents=True, exist_ok=True)+++def bind(source: Path, destination: Path, *, recursive: bool = False) -> None:+ require_directory(destination)+ subprocess.run(["/usr/bin/mount", "--rbind" if recursive else "--bind", str(source), str(destination)], check=True)+++def namespace_pid() -> int:+ state = json.loads((RUNTIME / "ready").read_text())+ pid = int(state["pid"])+ if pid <= 1 or Path(f"/proc/{pid}/ns/mnt").readlink().as_posix() != state["namespace"]:+ raise RuntimeError("Task filesystem namespace is no longer available")+ return pid+++def hold() -> None:+ bind(WORKSPACE, RUNTIME / "workspace")+ bind(Path("/tmp"), RUNTIME / "tmp", recursive=True)+ backing = RUNTIME / "workspace/.posthog/task-filesystem"+ bind(backing / "tmp", Path("/tmp"))+ bind(RUNTIME / "workspace", WORKSPACE)+ bind(backing / "var-tmp", Path("/var/tmp"))+ bind(backing / "home", Path("/root"))+ for name in RUNTIME_TMP_PATHS:+ destination = Path("/tmp") / name+ target = RUNTIME / "tmp" / name+ if destination.is_symlink():+ if destination.readlink() != target:+ raise RuntimeError(f"Unexpected runtime path: {destination}")+ elif destination.exists():+ raise RuntimeError(f"Task file conflicts with runtime path: {destination}")+ else:+ destination.symlink_to(target)+ ready = RUNTIME / "ready"+ temporary = RUNTIME / "ready.tmp"+ temporary.write_text(json.dumps({"pid": os.getpid(), "namespace": str(Path("/proc/self/ns/mnt").readlink())}))+ temporary.replace(ready)+ while True:+ signal.pause()+++def hold_after_user_mapping() -> None:+ if sys.stdin.read(1) != "1":+ raise RuntimeError("Task filesystem user mapping failed")+ arguments = ["/usr/bin/unshare", "--mount", "--propagation", "private", "/usr/bin/python3", "-I", __file__, "hold"]+ os.execv(arguments[0], arguments)+++def prepare_runtime_home(home: Path) -> None:+ require_directory(home / ".claude")+ settings = home / ".claude/posthog-session-settings"+ target = RUNTIME / "claude-session-settings"+ require_directory(target)+ target.chmod(0o700)+ if settings.is_symlink():+ if settings.readlink() != target:+ raise RuntimeError(f"Unexpected runtime path: {settings}")+ else:+ if settings.exists():+ shutil.rmtree(settings)+ settings.symlink_to(target, target_is_directory=True)+++def seed_home() -> None:+ require_directory(HOME_SEED)+ with tempfile.TemporaryDirectory(prefix=".home-", dir=HOME_SEED.parent) as temporary:+ copied = Path(temporary) / "home"+ subprocess.run(["/usr/bin/cp", "--archive", "--", "/root", str(copied)], check=True)+ shutil.rmtree(HOME_SEED)+ copied.rename(HOME_SEED)+++def prepare_home() -> None:+ home = STATE / "home"+ if home.resolve() != home:+ raise RuntimeError(f"Task filesystem path must be a real directory: {home}")+ if not home.is_dir():+ if (STATE / "version").exists() or not HOME_SEED.is_dir() or HOME_SEED.resolve() != HOME_SEED:+ raise RuntimeError("Task filesystem home must be seeded during image build")+ HOME_SEED.rename(home)+ prepare_runtime_home(home)+++def initialize(runtime: str) -> None:+ require_directory(RUNTIME)+ with (RUNTIME / "lock").open("w") as lock:+ fcntl.flock(lock, fcntl.LOCK_EX)+ if (RUNTIME / "ready").exists():+ try:+ namespace_pid()+ except (FileNotFoundError, ProcessLookupError, RuntimeError):+ (RUNTIME / "ready").unlink()+ else:+ return+ require_directory(STATE)+ version = STATE / "version"+ if version.is_symlink() or (version.exists() and version.read_text().strip() != VERSION):+ raise RuntimeError("Unsupported task filesystem version")+ for name in ("tmp", "var-tmp"):+ require_directory(STATE / name)+ (STATE / name).chmod(0o1777)+ prepare_home()+ for process_path in Path("/proc").iterdir():+ if not process_path.name.isdigit():+ continue+ try:+ if (process_path / "comm").read_text().strip() == "dockerd":+ raise RuntimeError("Docker must start after the task filesystem is initialized")+ except (FileNotFoundError, ProcessLookupError):+ continue+ arguments = ["/usr/bin/unshare"]+ if runtime == "gvisor":+ arguments.extend(["--user", "--keep-caps", "/usr/bin/python3", "-I", __file__, "map-user"])+ else:+ arguments.extend(["--mount", "--propagation", "private", "/usr/bin/python3", "-I", __file__, "hold"])+ with (RUNTIME / "setup.log").open("w") as log:+ process = subprocess.Popen(arguments, stdin=subprocess.PIPE, stdout=log, stderr=log, start_new_session=True)+ try:+ deadline = time.monotonic() + 15+ if runtime == "gvisor":+ while Path(f"/proc/{process.pid}/ns/user").readlink() == Path("/proc/self/ns/user").readlink():+ if process.poll() is not None or time.monotonic() >= deadline:+ raise RuntimeError("Task filesystem user namespace did not start")+ time.sleep(0.01)+ for name in ("uid_map", "gid_map"):+ mapping = ""+ for line in Path(f"/proc/self/{name}").read_text().splitlines():+ start, _, count = line.split()+ mapping += f"{start} {start} {count}\n"+ Path(f"/proc/{process.pid}/{name}").write_text(mapping)+ assert process.stdin is not None+ process.stdin.write(b"1")+ process.stdin.flush()+ assert process.stdin is not None+ process.stdin.close()+ while not (RUNTIME / "ready").exists():+ if process.poll() is not None or time.monotonic() >= deadline:+ raise RuntimeError(f"Task filesystem setup failed: {(RUNTIME / 'setup.log').read_text()[-2000:]}")+ time.sleep(0.05)+ namespace_pid()+ version.write_text(VERSION)+ (RUNTIME / "runtime").write_text(runtime)+ except BaseException:+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait()+ (RUNTIME / "ready").unlink(missing_ok=True)+ raise+++def enter(command: list[str]) -> None:+ if not (RUNTIME / "ready").exists() and not (STATE / "version").exists():+ os.execvp(command[0], command)+ pid = namespace_pid()+ if Path("/proc/self/ns/mnt").readlink() == Path(f"/proc/{pid}/ns/mnt").readlink():+ os.execvp(command[0], command)+ arguments = ["/usr/bin/nsenter", "--target", str(pid)]+ if (RUNTIME / "runtime").read_text() == "gvisor":+ arguments.append("--user")+ arguments.extend(["--mount", f"--wdns={os.getcwd()}", "--", *command])+ os.execv(arguments[0], arguments)+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("operation", choices=("seed-home", "initialize", "hold", "map-user", "enter"))+ parser.add_argument("arguments", nargs=argparse.REMAINDER)+ args = parser.parse_args()+ if args.operation == "seed-home":+ if args.arguments:+ parser.error("seed-home takes no arguments")+ seed_home()+ elif args.operation == "initialize":+ if args.arguments not in (["vm"], ["gvisor"]):+ parser.error("initialize requires vm or gvisor")+ initialize(args.arguments[0])+ elif args.operation == "hold":+ hold()+ elif args.operation == "map-user":+ hold_after_user_mapping()+ else:+ command = args.arguments[1:] if args.arguments[:1] == ["--"] else args.arguments+ if not command:+ parser.error("enter requires a command")+ enter(command)+++if __name__ == "__main__":+ main()diff --git a/products/tasks/backend/temporal/build_image/activities.py b/products/tasks/backend/temporal/build_image/activities.pyindex 6952334b3803..3e1692e783f2 100644--- a/products/tasks/backend/temporal/build_image/activities.py+++ b/products/tasks/backend/temporal/build_image/activities.py@@ -22,6 +22,7 @@ from products.tasks.backend.logic.services.image_spec import (validate_image_repository,validate_spec_buildable,)+from products.tasks.backend.logic.services.task_filesystem import TASK_FILESYSTEM_LOCAL_SCRIPT, TASK_FILESYSTEM_SCRIPTfrom products.tasks.backend.metrics import observe_custom_image_buildfrom products.tasks.backend.models import SandboxCustomImagefrom products.tasks.backend.temporal.observability import log_activity_execution@@ -271,6 +272,10 @@ def _compose_modal_image(if spec.repo_setup_commands:image = _attach_repo_warm_layer(image, spec)+ image = image.add_local_file(TASK_FILESYSTEM_LOCAL_SCRIPT, TASK_FILESYSTEM_SCRIPT, copy=True).run_commands(+ f"/usr/bin/python3 -I {TASK_FILESYSTEM_SCRIPT} seed-home"+ )+return image, app, base_image_referencediff --git a/products/tasks/backend/temporal/process_task/activities/run_wizard.py b/products/tasks/backend/temporal/process_task/activities/run_wizard.pyindex e2c17bbb4df2..6c5eb0b8422c 100644--- a/products/tasks/backend/temporal/process_task/activities/run_wizard.py+++ b/products/tasks/backend/temporal/process_task/activities/run_wizard.py@@ -35,7 +35,7 @@ _SANDBOX_EXEC_TIMEOUT_SECONDS = WIZARD_RUN_TIMEOUT_SECONDS + 120# The wizard's console output is written OUTSIDE the cloned repo working tree so it can never be# committed to the user's PR by mistake. The downstream agent reads it from this fixed path to# understand what the wizard did (and why it failed).-WIZARD_OUTPUT_DIR = "/tmp/wizard-cloud-run"+WIZARD_OUTPUT_DIR = "/tmp/workspace/.posthog/wizard-cloud-run"WIZARD_OUTPUT_LOG_PATH = f"{WIZARD_OUTPUT_DIR}/wizard-output.log"# The wizard's own verbose log — agent-level detail beyond stdout (e.g. which URL a failed API call@@ -116,7 +116,7 @@ def run_wizard(input: RunWizardInput) -> None:sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)command = _build_wizard_command(repo_path, ctx.team_id)- result = sandbox.execute(command, timeout_seconds=_SANDBOX_EXEC_TIMEOUT_SECONDS)+ result = sandbox.execute_in_task_filesystem(command, timeout_seconds=_SANDBOX_EXEC_TIMEOUT_SECONDS)# Persist the wizard's output outside the repo tree so the agent can consult what happened# without any chance of committing it. Written before the exit-code check so a failed run@@ -129,7 +129,9 @@ def run_wizard(input: RunWizardInput) -> None:# failed local run stays debuggable from the run's console log (it never reaches object# storage otherwise). `|| true` keeps a missing file — wizard exited before writing one —# from erroring the activity.- verbose = sandbox.execute(f"cat {shlex.quote(WIZARD_VERBOSE_LOG_PATH)} 2>/dev/null || true")+ verbose = sandbox.execute_in_task_filesystem(+ f"cat {shlex.quote(WIZARD_VERBOSE_LOG_PATH)} 2>/dev/null || true"+ )if verbose.stdout.strip():emit_agent_log(ctx.run_id, "debug", f"wizard verbose log ({WIZARD_VERBOSE_LOG_PATH}):\n{verbose.stdout}"diff --git a/products/tasks/backend/temporal/process_task/activities/start_dev_stack_preview.py b/products/tasks/backend/temporal/process_task/activities/start_dev_stack_preview.pyindex 2bffceccc46a..3d1697d3d64a 100644--- a/products/tasks/backend/temporal/process_task/activities/start_dev_stack_preview.py+++ b/products/tasks/backend/temporal/process_task/activities/start_dev_stack_preview.py@@ -155,7 +155,7 @@ def _launch_preview(input: StartDevStackPreviewInput) -> StartDevStackPreviewOutif uploaded.exit_code != 0:return StartDevStackPreviewOutput(started=False, reason=f"upload_exit_{uploaded.exit_code}")- result = sandbox.execute(+ result = sandbox.execute_in_task_filesystem(_launch_command(host=host, repo_path=sandbox_repo_path(input.repository)),timeout_seconds=LAUNCH_TIMEOUT_SECONDS,)diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_dev_stack_preview.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_dev_stack_preview.pyindex 74816790e749..ad658ef33e3f 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_dev_stack_preview.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_dev_stack_preview.py@@ -57,6 +57,7 @@ def _sandbox(return ExecutionResult(stdout="", stderr="", exit_code=launch_exit_code)sandbox.execute.side_effect = _execute+ sandbox.execute_in_task_filesystem.side_effect = _executemocker.patch(f"{MODULE}.Sandbox.get_by_id", return_value=sandbox)return sandbox@@ -192,7 +193,7 @@ def test_start_launches_the_stack_against_the_minted_preview_host(task_context,sandbox.create_preview_connect_credentials.assert_called_once()assert sandbox.create_preview_connect_credentials.call_args.kwargs["port"] == DEV_STACK_PREVIEW_PORTassert sandbox.write_file.call_args.args[0] == "/tmp/start-dev-stack-preview.sh"- launch_command = sandbox.execute.call_args.args[0]+ launch_command = sandbox.execute_in_task_filesystem.call_args.args[0]assert launch_command.startswith("/usr/bin/env -i ")assert "HOME=/root" in launch_commandassert "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/go/bin" in launch_commanddiff --git a/products/tasks/backend/tests/test_agentsh.py b/products/tasks/backend/tests/test_agentsh.pyindex 8c750d5130ad..1892b31ae4f4 100644--- a/products/tasks/backend/tests/test_agentsh.py+++ b/products/tasks/backend/tests/test_agentsh.py@@ -639,13 +639,15 @@ class TestModalSandboxAgentShWrapping(TestCase):if "--taskId" in command:launched.append(command)return ExecutionResult(stdout="", stderr="", exit_code=0)+ if AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX in command:+ return ExecutionResult(stdout=markers, stderr="", exit_code=0)+ if ENV_DISABLE_BUNDLED_SKILLS in command:+ return ExecutionResult(stdout="", stderr="", exit_code=0)if "chmod" in command: # gh shim installreturn ExecutionResult(stdout="", stderr="", exit_code=0)if command.startswith("bash /tmp/posthog-launch-preparation-"):return ExecutionResult(stdout="", stderr="", exit_code=0)- self.assertIn(ENV_DISABLE_BUNDLED_SKILLS, command)- self.assertIn("grep -q autoPublish", command)- return ExecutionResult(stdout=markers, stderr="", exit_code=0)+ raise AssertionError(f"Unexpected sandbox command: {command}")sandbox: ModalSandbox | DockerSandboxif provider == "modal":