Skip to content

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

fix(wizard): filter files before publishing changes (#98481)

Fernando Gomescc8357e9aef7
diff --git a/docs/internal/wizard-runs.md b/docs/internal/wizard-runs.md
index 7930109a5ba8..efd02b0f0d70 100644
--- a/docs/internal/wizard-runs.md
+++ b/docs/internal/wizard-runs.md
@@ -84,10 +84,13 @@ The Worker:
2. Provisions an isolated sandbox through the generic Tasks sandbox facade.
3. Clones the repository.
4. Runs the headless Wizard against the prepared workspace.
-5. Captures a binary Git diff.
+5. Replaces the Git index with publishable changes and captures a binary Git diff.
6. Creates a signed commit and opens or reuses a pull request when the workspace changed.
7. Destroys the sandbox.
+The publish step excludes ignored files, private environment files, agent instruction files, skills, common credentials, private keys, and new generated directories.
+It includes generated directories that the repository already tracks.
+
Tokens do not enter Temporal inputs, workflow history, run metadata, or logs.
Wizard owns the Worker command, environment, credentials, resource limits, timeouts, and diff behavior.
Tasks provides only generic repository-token and sandbox helpers through public facades.
diff --git a/products/wizard/backend/logic/workers/commands.py b/products/wizard/backend/logic/workers/commands.py
index a386399e21d8..b6abb6c1093e 100644
--- a/products/wizard/backend/logic/workers/commands.py
+++ b/products/wizard/backend/logic/workers/commands.py
@@ -115,8 +115,9 @@ def build_git_diff_command(repository_path: str) -> str:
# stdout into memory, so the byte cap is enforced sandbox-side. The sentinel extra byte lets
# the artifact step tell "at the limit" from "oversized"; && preserves git's exit code.
return (
- f"cd {shlex.quote(repository_path)} && git add -N --all && "
- f"git diff --binary --no-ext-diff HEAD > {shlex.quote(WIZARD_DIFF_OUTPUT_PATH)} && "
+ f"cd {shlex.quote(repository_path)} && "
+ "git diff --cached --binary --no-ext-diff --no-renames HEAD "
+ f"> {shlex.quote(WIZARD_DIFF_OUTPUT_PATH)} && "
f"head -c {MAX_GIT_DIFF_BYTES + 1} {shlex.quote(WIZARD_DIFF_OUTPUT_PATH)}"
)
diff --git a/products/wizard/backend/logic/workers/publishable_paths.py b/products/wizard/backend/logic/workers/publishable_paths.py
new file mode 100644
index 000000000000..9b073be99666
--- /dev/null
+++ b/products/wizard/backend/logic/workers/publishable_paths.py
@@ -0,0 +1,115 @@
+import shlex
+from collections.abc import Iterable, Sequence
+from fnmatch import fnmatchcase
+from pathlib import PurePosixPath
+
+_ENV_TEMPLATE_SUFFIXES = {".dist", ".example", ".sample", ".template"}
+_EXCLUDED_DIRECTORIES = {
+ ".agents",
+ ".aws",
+ ".azure",
+ ".claude",
+ ".codex",
+ ".docker",
+ ".cursor",
+ ".gemini",
+ ".gnupg",
+ ".kube",
+ ".m2",
+ ".opencode",
+ ".skills",
+ ".ssh",
+ ".windsurf",
+}
+_EXCLUDED_UNTRACKED_DIRECTORIES = {
+ ".astro",
+ ".cache",
+ ".mypy_cache",
+ ".next",
+ ".nuxt",
+ ".pytest_cache",
+ ".ruff_cache",
+ ".svelte-kit",
+ ".turbo",
+ ".venv",
+ "__pycache__",
+ "build",
+ "coverage",
+ "dist",
+ "logs",
+ "node_modules",
+ "venv",
+}
+_EXCLUDED_FILES = {
+ ".cursorrules",
+ ".dev.vars",
+ ".git-credentials",
+ ".netrc",
+ ".npmrc",
+ ".pypirc",
+ ".windsurfrules",
+ "agents.md",
+ "claude.md",
+ "gemini.md",
+ "skill.md",
+ "skills-lock.json",
+ "secrets.toml",
+}
+_EXCLUDED_CHILDREN = {
+ ".config": {"gcloud"},
+ ".github": {"copilot-instructions.md", "instructions", "prompts", "skills"},
+}
+_EXCLUDED_FILE_PATTERNS = (
+ "*.env.local",
+ "*.env.*.local",
+ "*.jks",
+ "*.key",
+ "*.keystore",
+ "*.p12",
+ "*.pem",
+ "*.pfx",
+ "*.sqlite",
+ "*.sqlite3",
+ "*.tfstate",
+ "*.tfstate.*",
+ "id_ed25519*",
+ "id_dsa*",
+ "id_ecdsa*",
+ "id_rsa*",
+ "service*account*.json",
+)
+
+
+def select_publishable_paths(tracked_paths: Iterable[str], untracked_paths: Iterable[str]) -> tuple[str, ...]:
+ tracked = (path for path in tracked_paths if _is_publishable_path(path, untracked=False))
+ untracked = (path for path in untracked_paths if _is_publishable_path(path, untracked=True))
+ return tuple(sorted(set(tracked) | set(untracked)))
+
+
+def literal_git_pathspec(paths: Sequence[str]) -> str:
+ return shlex.join(f":(top,literal){path}" for path in paths)
+
+
+def _is_publishable_path(path: str, *, untracked: bool) -> bool:
+ parsed = PurePosixPath(path)
+ if not parsed.parts or parsed.is_absolute() or ".." in parsed.parts:
+ return False
+
+ parts = tuple(part.casefold() for part in parsed.parts)
+ if any(part in _EXCLUDED_DIRECTORIES for part in parts):
+ return False
+ if untracked and any(part in _EXCLUDED_UNTRACKED_DIRECTORIES for part in parts[:-1]):
+ return False
+ if any(child in _EXCLUDED_CHILDREN.get(parent, ()) for parent, child in zip(parts, parts[1:])):
+ return False
+
+ name = parts[-1]
+ if name in _EXCLUDED_FILES or _is_private_environment_file(name):
+ return False
+ return not any(fnmatchcase(name, pattern) for pattern in _EXCLUDED_FILE_PATTERNS)
+
+
+def _is_private_environment_file(name: str) -> bool:
+ if PurePosixPath(name).suffix in _ENV_TEMPLATE_SUFFIXES:
+ return False
+ return name == ".envrc" or name == ".env" or name.startswith(".env.") or name.endswith(".env")
diff --git a/products/wizard/backend/logic/workers/repository_publisher.py b/products/wizard/backend/logic/workers/repository_publisher.py
index b6b608da56c1..833a4d166585 100644
--- a/products/wizard/backend/logic/workers/repository_publisher.py
+++ b/products/wizard/backend/logic/workers/repository_publisher.py
@@ -8,10 +8,12 @@ from posthog.models.integration import GitHubIntegration, Integration
from products.tasks.backend.facade.sandbox import SandboxBase, sandbox_repo_path
from products.wizard.backend.logic.workers.commands import bound_command_output
from products.wizard.backend.logic.workers.contracts import RepositoryPullRequest, SignedRepositoryCommit
+from products.wizard.backend.logic.workers.publishable_paths import literal_git_pathspec, select_publishable_paths
GIT_COMMAND_TIMEOUT_SECONDS = 60
GITHUB_MUTATION_TIMEOUT_SECONDS = 60
MAX_COMMIT_PAYLOAD_BYTES = 35 * 1024 * 1024
+_PRIVATE_KEY_HEADER_PATTERN = "-----BEGIN ([A-Z0-9 ]+ )?PRIVATE KEY-----"
_CREATE_COMMIT_MUTATION = """mutation($input: CreateCommitOnBranchInput!) {
createCommitOnBranch(input: $input) { commit { oid url } }
@@ -60,7 +62,6 @@ def create_signed_commit(
repository_name = _repository_parts(repository)
github = _github_integration(team_id, integration_id, source)
- _stage_all(sandbox, repository_path)
head_sha = _head_sha(sandbox, repository_path)
repository_id, existing_tip = _repository_and_branch_tip(
@@ -86,8 +87,35 @@ def create_signed_commit(
return SignedRepositoryCommit(repository=repository, branch=branch, commit_shas=(commit_sha,))
-def _stage_all(sandbox: SandboxBase, repository_path: str) -> None:
- _run_git(sandbox, repository_path, "add --all", "staging")
+def stage_publishable_changes(sandbox: SandboxBase, repository_path: str) -> tuple[str, ...]:
+ _run_git(sandbox, repository_path, "reset --quiet HEAD --", "staging reset")
+ tracked = _run_git(sandbox, repository_path, "diff --name-only -z --no-renames HEAD", "changed file detection")
+ untracked = _run_git(sandbox, repository_path, "ls-files --others --exclude-standard -z", "new file detection")
+ paths = select_publishable_paths(tracked.split("\0"), untracked.split("\0"))
+ if paths:
+ _run_git(sandbox, repository_path, f"add --all -- {literal_git_pathspec(paths)}", "staging")
+ private_keys = _staged_private_key_paths(sandbox, repository_path, paths)
+ if private_keys:
+ _run_git(
+ sandbox,
+ repository_path,
+ f"reset --quiet HEAD -- {literal_git_pathspec(sorted(private_keys))}",
+ "private key removal",
+ )
+ paths = tuple(path for path in paths if path not in private_keys)
+ return paths
+
+
+def _staged_private_key_paths(sandbox: SandboxBase, repository_path: str, paths: tuple[str, ...]) -> frozenset[str]:
+ pattern = shlex.quote(_PRIVATE_KEY_HEADER_PATTERN)
+ pathspec = literal_git_pathspec(paths)
+ output = _run_git(
+ sandbox,
+ repository_path,
+ f"grep --cached --name-only -z -I -E -e {pattern} -- {pathspec} || test $? -eq 1",
+ "private key detection",
+ )
+ return frozenset(output.split("\0")) - {""}
def _head_sha(sandbox: SandboxBase, repository_path: str) -> str:
diff --git a/products/wizard/backend/logic/workers/service.py b/products/wizard/backend/logic/workers/service.py
index 8f535158d3fb..0f0fbff38fb6 100644
--- a/products/wizard/backend/logic/workers/service.py
+++ b/products/wizard/backend/logic/workers/service.py
@@ -58,7 +58,12 @@ from products.wizard.backend.logic.workers.local_package import build_local_wiza
from products.wizard.backend.logic.workers.wizard_error_output import stderr_to_wizard_error_code
from products.wizard.backend.observability.service import wizard_observability
-from .repository_publisher import RepositoryPublishingError, create_pull_request, create_signed_commit
+from .repository_publisher import (
+ RepositoryPublishingError,
+ create_pull_request,
+ create_signed_commit,
+ stage_publishable_changes,
+)
logger = logging.getLogger(__name__)
@@ -247,6 +252,7 @@ def execute_wizard(request: WizardExecutionRequest) -> None:
def create_git_repository_handoff(request: GitRepositoryHandoffRequest) -> WizardWorkerResult:
sandbox = get_sandbox_class().get_by_id(request.sandbox_id)
+ stage_publishable_changes(sandbox, request.workspace_path)
diff_result = sandbox.execute(
build_git_diff_command(request.workspace_path),
diff --git a/products/wizard/backend/tests/runs/test_cloud_worker.py b/products/wizard/backend/tests/runs/test_cloud_worker.py
index 5c260b9d7519..69c53ee7e77e 100644
--- a/products/wizard/backend/tests/runs/test_cloud_worker.py
+++ b/products/wizard/backend/tests/runs/test_cloud_worker.py
@@ -391,6 +391,7 @@ def test_execute_wizard_surfaces_wizard_error_code(get_sandbox_class: MagicMock)
assert error.value.wizard_error_code == "PHW_DETECT_NO_POSTHOG_SDK"
+@patch("products.wizard.backend.logic.workers.service.stage_publishable_changes")
@patch("products.wizard.backend.logic.workers.service.create_pull_request")
@patch("products.wizard.backend.logic.workers.service.create_signed_commit")
@patch("products.wizard.backend.logic.workers.service.get_sandbox_class")
@@ -398,6 +399,7 @@ def test_git_repository_handoff_captures_diff_and_publishes_pull_request(
get_sandbox_class: MagicMock,
create_signed_commit: MagicMock,
create_pull_request: MagicMock,
+ stage_publishable_changes: MagicMock,
) -> None:
request = GitRepositoryHandoffRequest(
team_id=7,
@@ -425,11 +427,12 @@ def test_git_repository_handoff_captures_diff_and_publishes_pull_request(
result = create_git_repository_handoff(request)
assert result == WizardWorkerResult(diff=b"diff --git a/a b/a\n", pull_request=pull_request)
- assert "git add -N --all" in sandbox.execute.call_args_list[0].args[0]
+ assert "git diff --cached" in sandbox.execute.call_args_list[0].args[0]
assert WIZARD_DIFF_OUTPUT_PATH in sandbox.execute.call_args_list[0].args[0]
assert f"head -c {MAX_GIT_DIFF_BYTES + 1}" in sandbox.execute.call_args_list[0].args[0]
assert wizard_handoff_output_path(request.run_id) in sandbox.execute.call_args_list[1].args[0]
assert "head -c 60000" in sandbox.execute.call_args_list[1].args[0]
+ stage_publishable_changes.assert_called_once_with(sandbox, request.workspace_path)
create_signed_commit.assert_called_once_with(
sandbox,
team_id=request.team_id,
@@ -457,6 +460,7 @@ def test_git_repository_handoff_captures_diff_and_publishes_pull_request(
_execution_result(stdout=" \n"),
),
)
+@patch("products.wizard.backend.logic.workers.service.stage_publishable_changes")
@patch("products.wizard.backend.logic.workers.service.create_pull_request")
@patch("products.wizard.backend.logic.workers.service.create_signed_commit")
@patch("products.wizard.backend.logic.workers.service.get_sandbox_class")
@@ -466,6 +470,7 @@ def test_git_repository_handoff_uses_generic_body_when_handoff_is_unavailable(
get_sandbox_class: MagicMock,
create_signed_commit: MagicMock,
create_pull_request: MagicMock,
+ _stage_publishable_changes: MagicMock,
handoff_result: SimpleNamespace,
) -> None:
request = GitRepositoryHandoffRequest(
@@ -487,11 +492,13 @@ def test_git_repository_handoff_uses_generic_body_when_handoff_is_unavailable(
handoff_body_fallback.assert_called_once_with(request.team_id, request.run_id)
+@patch("products.wizard.backend.logic.workers.service.stage_publishable_changes")
@patch("products.wizard.backend.logic.workers.service.create_pull_request")
@patch("products.wizard.backend.logic.workers.service.get_sandbox_class")
def test_git_repository_handoff_skips_publish_without_changes(
get_sandbox_class: MagicMock,
create_pull_request: MagicMock,
+ _stage_publishable_changes: MagicMock,
) -> None:
request = GitRepositoryHandoffRequest(
team_id=7,
diff --git a/products/wizard/backend/tests/runs/test_repository_publisher.py b/products/wizard/backend/tests/runs/test_repository_publisher.py
index 8ceca06fced4..37dc2e6f2f2b 100644
--- a/products/wizard/backend/tests/runs/test_repository_publisher.py
+++ b/products/wizard/backend/tests/runs/test_repository_publisher.py
@@ -1,9 +1,12 @@
import base64
+import subprocess
+from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
-from products.wizard.backend.logic.workers.repository_publisher import create_signed_commit
+from products.wizard.backend.logic.workers.publishable_paths import select_publishable_paths
+from products.wizard.backend.logic.workers.repository_publisher import create_signed_commit, stage_publishable_changes
def _execution_result(*, stdout: str = "", exit_code: int = 0) -> SimpleNamespace:
@@ -14,6 +17,130 @@ def _graphql_response(payload: dict[str, object]) -> SimpleNamespace:
return SimpleNamespace(status_code=200, json=lambda: payload)
+def _without_output_bound(command: str, **_: object) -> str:
+ return command
+
+
+def _git(repository: Path, *arguments: str, input: str | None = None) -> str:
+ return subprocess.run(
+ [
+ "git",
+ "-C",
+ str(repository),
+ "-c",
+ "user.name=Wizard test",
+ "-c",
+ "-c",
+ "commit.gpgsign=false",
+ *arguments,
+ ],
+ input=input,
+ capture_output=True,
+ text=True,
+ check=True,
+ timeout=10,
+ ).stdout
+
+
+def test_publishable_paths_keep_framework_source_and_exclude_workspace_files() -> None:
+ tracked_paths = (
+ "build/tracked-output.js",
+ "dist/tracked-output.js",
+ )
+ untracked_paths = (
+ "src/config.env.ts",
+ "src/credentials.ts",
+ "src/secrets.py",
+ "config/initializers/posthog.rb",
+ "app/Providers/PostHogServiceProvider.php",
+ "lib/main.dart",
+ "ios/App/PostHogSetup.swift",
+ "app/src/main/PostHog.kt",
+ "Program.cs",
+ "cmd/posthog/main.go",
+ "src/posthog.rs",
+ ".env.example",
+ ".env",
+ ".dev.vars",
+ "apps/web/.env.production.local",
+ "production.env",
+ ".streamlit/secrets.toml",
+ ".docker/config.json",
+ ".gnupg/private-keys-v1.d/key",
+ ".kube/config",
+ ".m2/settings.xml",
+ ".config/gcloud/application_default_credentials.json",
+ ".agents/skills/posthog/SKILL.md",
+ ".claude/skills/posthog/setup.py",
+ ".github/skills/posthog/SKILL.md",
+ "nested/AGENTS.md",
+ "node_modules/posthog-js/index.js",
+ "apps/web/.next/server/app.js",
+ "backend/.venv/lib/posthog.py",
+ "dist/index.js",
+ "build/output.txt",
+ "id_dsa",
+ "id_ecdsa.pub",
+ )
+
+ assert select_publishable_paths(tracked_paths, untracked_paths) == (
+ ".env.example",
+ "Program.cs",
+ "app/Providers/PostHogServiceProvider.php",
+ "app/src/main/PostHog.kt",
+ "build/tracked-output.js",
+ "cmd/posthog/main.go",
+ "config/initializers/posthog.rb",
+ "dist/tracked-output.js",
+ "ios/App/PostHogSetup.swift",
+ "lib/main.dart",
+ "src/config.env.ts",
+ "src/credentials.ts",
+ "src/posthog.rs",
+ "src/secrets.py",
+ )
+
+
+def test_stage_publishable_changes_replaces_existing_staging(tmp_path: Path) -> None:
+ repository = tmp_path / "repository"
+ repository.mkdir()
+ _git(repository, "init")
+ (repository / "README.md").write_text("Example project\n")
+ _git(repository, "add", "--all")
+ _git(repository, "commit", "-m", "Initial commit")
+
+ paths = (
+ "src/component's name.tsx",
+ "src/private-key.txt",
+ ".env",
+ ".agents/skills/posthog/SKILL.md",
+ )
+ for name in paths:
+ path = repository / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("changed\n")
+ (repository / "src/private-key.txt").write_text("-----BEGIN PRIVATE KEY-----\nprivate\n")
+ _git(repository, "add", "--all")
+
+ def execute(command: str, *, timeout_seconds: int) -> SimpleNamespace:
+ result = subprocess.run(["bash", "-c", command], capture_output=True, text=True, timeout=timeout_seconds)
+ assert result.returncode == 0, result.stderr
+ return SimpleNamespace(stdout=result.stdout, exit_code=result.returncode)
+
+ sandbox = MagicMock()
+ sandbox.execute.side_effect = execute
+
+ with patch(
+ "products.wizard.backend.logic.workers.repository_publisher.bound_command_output",
+ side_effect=_without_output_bound,
+ ):
+ selected = stage_publishable_changes(sandbox, str(repository))
+
+ assert selected == ("src/component's name.tsx",)
+ assert _git(repository, "diff", "--cached", "--name-only").splitlines() == ["src/component's name.tsx"]
+
+
@patch("products.wizard.backend.logic.workers.repository_publisher.GitHubIntegration")
@patch("products.wizard.backend.logic.workers.repository_publisher.Integration.objects.filter")
def test_create_signed_commit_strips_head_sha_and_supports_binary_files(
@@ -31,7 +158,6 @@ def test_create_signed_commit_strips_head_sha_and_supports_binary_files(
staged_contents = base64.b64encode(b"\x00\x01\x02").decode()
sandbox = MagicMock()
sandbox.execute.side_effect = [
- _execution_result(),
_execution_result(stdout="7a6e71985f4e0058f10517fc662813a39818f805\n"),
_execution_result(stdout="A\0src/config.py\0"),
_execution_result(stdout=staged_contents),