: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
fix(hogli): commit pr-assets uploads via signed graphql (#78999)
Raúl Negrón-Otero20df8d36eafc
diff --git a/tools/hogli-commands/hogli_commands/github_auth.py b/tools/hogli-commands/hogli_commands/github_auth.pyindex d325c8135fc7..5afcb332951c 100644--- a/tools/hogli-commands/hogli_commands/github_auth.py+++ b/tools/hogli-commands/hogli_commands/github_auth.py@@ -1,7 +1,7 @@"""Shared GitHub auth for hogli commands: a token from the env or gh CLI, plus API headers.-Centralizes the one decision (how to source a github.com token and what REST headers to-send) so callers like db:restore-test-db and pr:upload-image don't each reimplement it.+Centralizes the one decision (how to source a github.com token and what headers to send)+so callers like db:restore-test-db and pr:upload-image don't each reimplement it."""from __future__ import annotations@@ -38,7 +38,10 @@ def github_token() -> str | None:def github_headers(token: str | None) -> dict[str, str]:- """Standard GitHub REST API headers, with Bearer auth when a token is available."""+ """Standard GitHub API headers, with Bearer auth when a token is available.++ The REST version pin is inert on GraphQL requests, which ignore unknown headers.+ """headers = {"Accept": "application/vnd.github+json","X-GitHub-Api-Version": "2022-11-28",diff --git a/tools/hogli-commands/hogli_commands/pr_assets.py b/tools/hogli-commands/hogli_commands/pr_assets.pyindex eef5096014cc..2f7f0d1f3189 100644--- a/tools/hogli-commands/hogli_commands/pr_assets.py+++ b/tools/hogli-commands/hogli_commands/pr_assets.py@@ -1,41 +1,71 @@-"""Shared client for the public PostHog/pr-assets evidence repo.--pr:upload-image and pr:upload-video both publish files here through the GitHub-contents API; this module owns the storage concerns they share - the repo-constant, the public-and-permanent warning, the object-key scheme, path-validation, and the upload PUT with its concurrent-commit retry. The commands-keep what differs between them: allowed extensions, the markdown they print,-and their flags.+"""Storage for the public PostHog/pr-assets evidence repo.++pr:upload-image and pr:upload-video both publish here. This module owns every storage+concern behind a single call: sourcing a token, naming objects, committing them, and+handing back the URLs that render in a PR. Callers never see keys, commit shas, or the+GitHub API, so they cannot assemble a URL that does not exist.++Commits go through the GraphQL createCommitOnBranch mutation rather than the REST+contents API because the repo requires verified signatures. GraphQL commits under+GitHub's own signing key; the REST path commits as the caller, unsigned, and the+ruleset rejects it."""from __future__ import annotationsimport base64+from collections.abc import Sequence+from dataclasses import dataclassfrom datetime import UTC, datetimefrom pathlib import Path-from typing import Final+from typing import Any, Finalfrom uuid import uuid4import clickimport requests-from hogli_commands.github_auth import github_headers+from hogli_commands.github_auth import github_headers, github_tokenREPO: Final = "PostHog/pr-assets"+_OWNER, _NAME = REPO.split("/")+_API: Final = "https://api.github.com/graphql"+# Each retry re-reads the branch head, and that round trip is the backoff.+_MAX_ATTEMPTS: Final = 5+PUBLIC_WARNING: Final = ("⚠ PUBLIC + PERMANENT upload to PostHog/pr-assets.\n"" SHA-pinned URLs keep serving even after the file is deleted, so an upload cannot be taken back.\n"" Never upload customer data, secrets, tokens, or internal-only information.")+_HEAD_QUERY: Final = """+query($owner: String!, $name: String!) {+ repository(owner: $owner, name: $name) {+ defaultBranchRef { name target { oid } }+ }+}+"""-def escape_markdown_label(text: str) -> str:- """Escape alt or link text so it cannot truncate the markdown embed.+_COMMIT_MUTATION: Final = """+mutation($input: CreateCommitOnBranchInput!) {+ createCommitOnBranch(input: $input) { commit { oid } }+}+"""- Backslashes first: a raw backslash before an escaped bracket would read as a- literal backslash plus an unescaped `]` and close the label early.- """- return text.replace("\\", "\\\\").replace("]", "\\]")++@dataclass(frozen=True, kw_only=True)+class _Head:+ branch: str+ oid: str+++class _OperationFailed(Exception):+ """A GraphQL response that carried an errors array."""++ def __init__(self, errors: Sequence[dict[str, Any]]) -> None:+ self.types = {error.get("type") for error in errors}+ self.messages = [str(error.get("message", "")) for error in errors]+ super().__init__("; ".join(self.messages))def make_key(ext: str) -> str:@@ -63,51 +93,121 @@ def validate(path: Path, allowed_exts: frozenset[str], max_mb: int) -> str:return ext+def publish(paths: Sequence[Path], *, message: str) -> list[str]:+ """Commit every path in one signed commit, returning a raw URL per path in input order.++ URLs are pinned to the created commit, so they keep serving even after the file is+ moved or deleted.+ """+ token = github_token()+ if token is None:+ raise click.ClickException(+ "no GitHub token found. Set GH_TOKEN or GITHUB_TOKEN, or install gh "+ "(https://cli.github.com/) and run `gh auth login`."+ )+ additions = [+ {"path": make_key(path.suffix.lower().lstrip(".")), "contents": _encode_base64(path)} for path in paths+ ]+ oid = _commit(requests.Session(), token, additions, message)+ return [f"https://raw.githubusercontent.com/{REPO}/{oid}/{addition['path']}" for addition in additions]++def _encode_base64(path: Path) -> str:"""Base64-encode the file as a single newline-free line.- The contents API wants raw base64 with no line breaks; ``b64encode`` (unlike- ``encodebytes``) never inserts them.+ GraphQL wants raw base64 with no line breaks; ``b64encode`` (unlike ``encodebytes``)+ never inserts them."""return base64.b64encode(path.read_bytes()).decode("ascii")-def _put(session: requests.Session, url: str, token: str, body: dict[str, str]) -> requests.Response:- """PUT to the contents API, turning a network error into a friendly ClickException."""+def _graphql(session: requests.Session, token: str, query: str, variables: dict[str, Any]) -> dict[str, Any]:+ """POST a GraphQL document and return its ``data``.++ GraphQL answers HTTP 200 even when the operation fails, so the errors array decides+ the outcome and the status code only catches transport and auth failures.+ """try:- return session.put(url, headers=github_headers(token), json=body, timeout=120)+ resp = session.post(+ _API, headers=github_headers(token), json={"query": query, "variables": variables}, timeout=120+ )except requests.RequestException as exc:raise click.ClickException(f"GitHub request failed: {exc}")+ if resp.status_code in (401, 403):+ raise click.ClickException(_denied_message())+ if not resp.ok:+ raise click.ClickException(f"GitHub returned HTTP {resp.status_code}")-def upload(path: Path, key: str, token: str, session: requests.Session, message: str) -> str:- """PUT the file to the contents API, returning the created commit sha.+ try:+ body = resp.json()+ except ValueError as exc:+ raise click.ClickException(f"GitHub returned a non-JSON response: {exc}")- Retries once on HTTP 409 with the same key, since concurrent commits to the repo's- default branch can race.- """- url = f"https://api.github.com/repos/{REPO}/contents/{key}"- body = {"message": message, "content": _encode_base64(path)}+ if errors := body.get("errors"):+ raise _OperationFailed(errors)+ data = body.get("data")+ if not isinstance(data, dict):+ raise click.ClickException("GitHub returned a response carrying no data")+ return data- resp = _put(session, url, token, body)- if resp.status_code == 409:- # a concurrent commit to the default branch raced us; retry once with the same key- resp = _put(session, url, token, body)- if resp.status_code in (403, 404):- raise click.ClickException(_denied_message(path))- if not resp.ok:- raise click.ClickException(f"upload of {path.name} failed (HTTP {resp.status_code})")+def _read_head(session: requests.Session, token: str) -> _Head:+ # _OperationFailed is the retry signal for the mutation; a failed read has nothing to retry.try:- return resp.json()["commit"]["sha"]- except (ValueError, KeyError, TypeError) as exc:- raise click.ClickException(f"GitHub returned an unexpected response uploading {path.name}: {exc}")+ data = _graphql(session, token, _HEAD_QUERY, {"owner": _OWNER, "name": _NAME})+ except _OperationFailed as exc:+ raise click.ClickException(f"could not read {REPO}: {exc}")+ ref = (data.get("repository") or {}).get("defaultBranchRef") or {}+ branch, oid = ref.get("name"), (ref.get("target") or {}).get("oid")+ if not branch or not oid:+ raise click.ClickException(f"could not read the default branch of {REPO}")+ return _Head(branch=branch, oid=oid)+++def _commit(session: requests.Session, token: str, additions: list[dict[str, str]], message: str) -> str:+ """Create one signed commit carrying every addition, returning its oid.++ The mutation names the head it expects to extend, so a commit that lands first fails+ this one with STALE_DATA and re-reading the head is the whole recovery. Committing+ every file together keeps that rare: one invocation makes one commit.+ """+ head = _read_head(session, token)+ for _ in range(_MAX_ATTEMPTS):+ variables = {+ "input": {+ "branch": {"repositoryNameWithOwner": REPO, "branchName": head.branch},+ "message": {"headline": message},+ "expectedHeadOid": head.oid,+ "fileChanges": {"additions": additions},+ }+ }+ try:+ data = _graphql(session, token, _COMMIT_MUTATION, variables)+ except _OperationFailed as exc:+ if "STALE_DATA" in exc.types:+ head = _read_head(session, token)+ continue+ # The head read above resolved this branch, so GitHub calling it missing here+ # means the token can read the repo but not write to it.+ if any("Branch not found" in reported for reported in exc.messages):+ raise click.ClickException(_denied_message())+ raise click.ClickException(f"upload failed: {exc}")++ oid = ((data.get("createCommitOnBranch") or {}).get("commit") or {}).get("oid")+ if not oid:+ raise click.ClickException("GitHub returned a commit carrying no sha")+ return oid++ raise click.ClickException(+ f"{REPO} moved under the upload {_MAX_ATTEMPTS} times in a row; nothing was published, so try again"+ )-def _denied_message(path: Path) -> str:- """Explain a 403/404: the token can't write to pr-assets (not an org member, or missing scope)."""+def _denied_message() -> str:+ """Explain a rejected write: the token can't write to pr-assets (not an org member, or missing scope)."""return (- f"upload of {path.name} was denied. Writing to {REPO} needs write access to a public PostHog repo: "+ f"upload denied. Writing to {REPO} needs write access to a public PostHog repo: ""confirm your token is a PostHog org account with the `repo` scope ""(gh users: `gh auth refresh -s repo`; or set GH_TOKEN to a PAT with the repo scope).")diff --git a/tools/hogli-commands/hogli_commands/pr_upload.py b/tools/hogli-commands/hogli_commands/pr_upload.pynew file mode 100644index 000000000000..4887c8fc984b--- /dev/null+++ b/tools/hogli-commands/hogli_commands/pr_upload.py@@ -0,0 +1,68 @@+"""The shared body of pr:upload-image and pr:upload-video.++The two commands differ only in what they accept and how they render what they+published. ``AssetKind`` carries those differences; ``run`` performs the flow they+share: warn, validate, gate on --yes, publish, print markdown.+"""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path++import click++from hogli_commands import pr_assets+++@dataclass(frozen=True, kw_only=True)+class AssetKind:+ """What one upload command accepts, and how it renders the result."""++ noun: str+ caption_flag: str+ allowed_exts: frozenset[str]+ max_mb: int+ commit_message: str+ markdown: str # formatted with `label` and `url`+++def escape_markdown_label(text: str) -> str:+ """Escape caption text so it cannot truncate the markdown it sits in.++ Backslashes first: a raw backslash before an escaped bracket would read as a+ literal backslash plus an unescaped `]` and close the label early.+ """+ return text.replace("\\", "\\\\").replace("]", "\\]")+++def run(files: tuple[Path, ...], caption: str | None, yes: bool, kind: AssetKind) -> None:+ """Publish every file and print one markdown line each to stdout."""+ click.secho(pr_assets.PUBLIC_WARNING, fg="yellow", bold=True, err=True)++ if caption is not None and len(files) > 1:+ raise click.ClickException(+ f"{kind.caption_flag} captions a single {kind.noun}; drop it to caption each file with its stem"+ )++ for path in files:+ pr_assets.validate(path, kind.allowed_exts, kind.max_mb)++ # Deliberate speed bump: make the caller read the warning above and re-run to confirm.+ if not yes:+ click.secho(+ f"\nNothing uploaded. If the {kind.noun} is safe to publish (no customer data, secrets, or "+ "internal info), re-run the same command with --yes to confirm.",+ fg="yellow",+ err=True,+ )+ raise SystemExit(1)++ click.secho(f"Uploading to {pr_assets.REPO} …", fg="cyan", err=True)+ urls = pr_assets.publish(files, message=kind.commit_message)++ for path, url in zip(files, urls, strict=True):+ label = caption if caption is not None else path.stem+ # stdout carries only the markdown, so callers can pipe it+ click.echo(kind.markdown.format(label=escape_markdown_label(label), url=url))+ click.secho(f"✓ uploaded {path.name}", fg="green", err=True)diff --git a/tools/hogli-commands/hogli_commands/tests/test_pr_assets.py b/tools/hogli-commands/hogli_commands/tests/test_pr_assets.pyindex e87f25850c2c..893b40dcf79f 100644--- a/tools/hogli-commands/hogli_commands/tests/test_pr_assets.py+++ b/tools/hogli-commands/hogli_commands/tests/test_pr_assets.py@@ -1,21 +1,25 @@-"""Tests for the shared pr-assets client.+"""Tests for the shared pr-assets storage module.-Moved here with the plumbing when it was extracted from upload_image: the exact key-shape, the base64 content body, the single retry on a concurrent-commit 409, the-denied-PUT guidance, and the validation gates both upload commands share.+These pin the storage contract both upload commands depend on: one signed commit per+invocation, commit-pinned URLs in input order, the GraphQL failure handling that a+status-code check would miss, the stale-head retry, and the validation gates."""from __future__ import annotationsimport reimport base64+from collections.abc import Iterator+from contextlib import contextmanagerfrom pathlib import Pathfrom types import SimpleNamespace+from typing import Anyimport pytest-from unittest.mock import Mock+from unittest.mock import Mock, patch-from hogli_commands import pr_assets+import click+from hogli_commands import github_auth, pr_assets_KEY_RE = r"\d{4}/\d{2}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"_PNG_ONLY = frozenset({"png"})@@ -28,72 +32,131 @@ def png(tmp_path: Path) -> Path:return path-def _resp(status: int, sha: str | None = None) -> SimpleNamespace:- return SimpleNamespace(- status_code=status,- ok=status < 400,- json=lambda: {"commit": {"sha": sha}} if sha is not None else {},- )+def token(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("GH_TOKEN", "tok")+++def _resp(payload: dict[str, Any], status: int = 200) -> SimpleNamespace:+ return SimpleNamespace(status_code=status, ok=status < 400, json=lambda: payload)+++def _head(oid: str = "head1", branch: str = "main") -> SimpleNamespace:+ return _resp({"data": {"repository": {"defaultBranchRef": {"name": branch, "target": {"oid": oid}}}}})++def _committed(oid: str) -> SimpleNamespace:+ return _resp({"data": {"createCommitOnBranch": {"commit": {"oid": oid}}}})-def _session(*responses: SimpleNamespace) -> Mock:++def _failed(**error: str) -> SimpleNamespace:+ return _resp({"data": {"createCommitOnBranch": None}, "errors": [error]})+++def _stale() -> SimpleNamespace:+ return _failed(type="STALE_DATA", message='Expected branch to point to "x" but it did not.')+++@contextmanager+def _session(*responses: SimpleNamespace) -> Iterator[Mock]:session = Mock()- session.put.side_effect = responses- return session+ session.post.side_effect = list(responses)+ with patch.object(pr_assets.requests, "Session", return_value=session):+ yield session+++def _additions(session: Mock) -> list[dict[str, str]]:+ return session.post.call_args.kwargs["json"]["variables"]["input"]["fileChanges"]["additions"]+++def _expected_heads(session: Mock) -> list[str]:+ return [+ call.kwargs["json"]["variables"]["input"]["expectedHeadOid"]+ for call in session.post.call_args_list+ if "createCommitOnBranch" in call.kwargs["json"]["query"]+ ]+++def test_publishes_every_file_in_one_commit_with_urls_in_input_order(png: Path, tmp_path: Path, token: None) -> None:+ # One commit per invocation is what keeps concurrent uploads from colliding on expectedHeadOid.+ second = tmp_path / "after.png"+ second.write_bytes(b"\x89PNG second")++ with _session(_head(), _committed("c0ffee")) as session:+ urls = pr_assets.publish([png, second], message="add screenshot")++ assert session.post.call_count == 2 # one head read, one mutation+ additions = _additions(session)+ assert len(additions) == 2+ assert [url.split("/c0ffee/")[1] for url in urls] == [addition["path"] for addition in additions]+ assert all(url.startswith("https://raw.githubusercontent.com/PostHog/pr-assets/c0ffee/") for url in urls)+++def test_sends_newline_free_base64_under_a_dated_key(png: Path, token: None) -> None:+ with _session(_head(), _committed("c0ffee")) as session:+ pr_assets.publish([png], message="add screenshot")++ addition = _additions(session)[0]+ assert addition["contents"] == base64.b64encode(png.read_bytes()).decode()+ assert "\n" not in addition["contents"] # GraphQL rejects line-wrapped base64+ assert re.fullmatch(_KEY_RE + r"\.png", addition["path"])++def test_operation_failure_is_surfaced_even_though_http_is_200(png: Path, token: None) -> None:+ # GraphQL answers 200 with an errors array. Deciding on the status code would treat this+ # as a success and print markdown pointing at a commit that was never created.+ with _session(_head(), _failed(type="FORBIDDEN", message="nope")):+ with pytest.raises(click.ClickException, match="upload failed"):+ pr_assets.publish([png], message="add screenshot")-def test_make_key_shape() -> None:- # YYYY/MM/<uuid4>.<ext>: the README-pinned layout keeps the tree browsable and prunable.- assert re.fullmatch(_KEY_RE + r"\.png", pr_assets.make_key("png"))+ "before_failure",+ [[], [_head(), _stale()]],+ ids=["first_read", "retry_read"],+)+def test_failed_head_read_stays_a_plain_error(png: Path, token: None, before_failure: list[SimpleNamespace]) -> None:+ # A rate limit or a revoked token answers the head read with an errors array. Letting+ # that escape prints a traceback instead of a message telling the caller what to do.+ with _session(*before_failure, _failed(type="RATE_LIMITED", message="API rate limit exceeded")):+ with pytest.raises(click.ClickException, match="could not read PostHog/pr-assets"):+ pr_assets.publish([png], message="add screenshot")-def test_upload_puts_base64_body_and_returns_sha(png: Path) -> None:- session = _session(_resp(201, "deadbeef"))- sha = pr_assets.upload(png, "2026/07/abc.png", "tok", session, message="add screenshot")- assert sha == "deadbeef"- url = session.put.call_args.args[0]- assert url == "https://api.github.com/repos/PostHog/pr-assets/contents/2026/07/abc.png"- body = session.put.call_args.kwargs["json"]- assert body["message"] == "add screenshot"- assert body["content"] == base64.b64encode(png.read_bytes()).decode()- assert "\n" not in body["content"] # the contents API rejects line-wrapped base64- assert session.put.call_args.kwargs["headers"]["Authorization"] == "Bearer tok"+def test_stale_head_is_retried_against_a_freshly_read_head(png: Path, token: None) -> None:+ with _session(_head("head1"), _stale(), _head("head2"), _committed("c0ffee")) as session:+ urls = pr_assets.publish([png], message="add screenshot")+ assert "/c0ffee/" in urls[0]+ assert _expected_heads(session) == ["head1", "head2"] # reusing head1 would fail forever-def test_upload_retries_once_on_409_with_same_key(png: Path) -> None:- session = _session(_resp(409), _resp(201, "sha2"))- sha = pr_assets.upload(png, "2026/07/abc.png", "tok", session, message="add screenshot")- assert sha == "sha2"- assert session.put.call_count == 2- # both attempts target the identical key; a fresh key on retry would orphan the first- urls = {call.args[0] for call in session.put.call_args_list}- assert urls == {"https://api.github.com/repos/PostHog/pr-assets/contents/2026/07/abc.png"}+def test_gives_up_after_repeated_stale_heads(png: Path, token: None) -> None:+ losing_race = [_head(f"head{attempt}") for attempt in range(pr_assets._MAX_ATTEMPTS)]+ responses = [_head("head0")]+ for head in losing_race:+ responses += [_stale(), head]+ with _session(*responses):+ with pytest.raises(click.ClickException, match="nothing was published"):+ pr_assets.publish([png], message="add screenshot")-def test_upload_gives_up_after_second_409(png: Path) -> None:- session = _session(_resp(409), _resp(409))- with pytest.raises(pr_assets.click.ClickException):- pr_assets.upload(png, "2026/07/x.png", "tok", session, message="add screenshot")- assert session.put.call_count == 2 # one retry, then surface the failure+def test_branch_not_found_after_a_successful_head_read_reports_write_access(png: Path, token: None) -> None:+ # GitHub returns "Branch not found" both for a missing branch and for a token that cannot+ # write. The head read already resolved this branch, so it can only be permissions.+ with _session(_head(), _failed(type="NOT_FOUND", message="Branch not found")):+ with pytest.raises(click.ClickException, match="write access"):+ pr_assets.publish([png], message="add screenshot")[email protected]("status", [403, 404], ids=["forbidden", "not_found"])-def test_permission_denied_points_at_org_access(png: Path, status: int) -> None:- # A denied PUT must explain the write-access fix, not surface a raw error; this is the- # "only PostHog org members can write" boundary.- session = _session(_resp(status))- with pytest.raises(pr_assets.click.ClickException, match="PostHog org"):- pr_assets.upload(png, "2026/07/x.png", "tok", session, message="add screenshot")+def test_missing_token_names_how_to_supply_one(png: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("GH_TOKEN", raising=False)+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)+ monkeypatch.setattr(github_auth.shutil, "which", lambda _: None) # no env, no gh -> no token-def test_upload_wraps_unexpected_response(png: Path) -> None:- # A 2xx whose body isn't the contents-API shape must surface as a ClickException, not a- # raw KeyError traceback.- session = _session(_resp(201)) # json() -> {} with no commit.sha- with pytest.raises(pr_assets.click.ClickException, match="unexpected response"):- pr_assets.upload(png, "2026/07/x.png", "tok", session, message="add screenshot")+ with pytest.raises(click.ClickException, match="GH_TOKEN"):+ pr_assets.publish([png], message="add screenshot")def test_validate_rejects_symlink_before_reading_target(tmp_path: Path) -> None:@@ -103,20 +166,20 @@ def test_validate_rejects_symlink_before_reading_target(tmp_path: Path) -> None:target.write_bytes(b"SECRET=1")link = tmp_path / "screenshot.png"link.symlink_to(target)- with pytest.raises(pr_assets.click.ClickException, match="symlink"):+ with pytest.raises(click.ClickException, match="symlink"):pr_assets.validate(link, _PNG_ONLY, 10)def test_validate_rejects_extension_outside_allowlist(tmp_path: Path) -> None:path = tmp_path / "clip.mp4"path.write_bytes(b"data")- with pytest.raises(pr_assets.click.ClickException, match="unsupported"):+ with pytest.raises(click.ClickException, match="unsupported"):pr_assets.validate(path, _PNG_ONLY, 10)def test_validate_rejects_oversized_file(tmp_path: Path, png: Path) -> None:big = tmp_path / "big.png"big.write_bytes(b"\x00" * (1024 * 1024 + 1))- with pytest.raises(pr_assets.click.ClickException, match="exceeds the 1 MB limit"):+ with pytest.raises(click.ClickException, match="exceeds the 1 MB limit"):pr_assets.validate(big, _PNG_ONLY, 1)assert pr_assets.validate(png, _PNG_ONLY, 1) == "png"diff --git a/tools/hogli-commands/hogli_commands/tests/test_upload_image.py b/tools/hogli-commands/hogli_commands/tests/test_upload_image.pyindex f5be4d5cb452..211462247b23 100644--- a/tools/hogli-commands/hogli_commands/tests/test_upload_image.py+++ b/tools/hogli-commands/hogli_commands/tests/test_upload_image.py@@ -1,25 +1,26 @@"""Tests for hogli pr:upload-image.The framework's parametrized ``--help`` test covers command wellformedness, and the-shared upload plumbing (key shape, base64 body, 409 retry, validation gates) is pinned-in ``test_pr_assets``. These guard what is command-specific: the SHA-pinned image-markdown that lands on stdout and nothing else, the --alt contract, the extension-allowlist, and the --yes confirmation gate. Token sourcing lives in ``test_github_auth``.+storage contract (single commit, pinned URLs, retries, validation gates) is pinned in+``test_pr_assets``. These guard what is command-specific: the image markdown that lands+on stdout and nothing else, the --alt contract, the extension allowlist, and the --yes+confirmation gate."""from __future__ import annotations-import re+from collections.abc import Iterator+from contextlib import contextmanagerfrom pathlib import Path-from types import SimpleNamespaceimport pytestfrom unittest.mock import Mock, patch+import clickfrom click.testing import CliRunner-from hogli_commands import github_auth, pr_assets, upload_image+from hogli_commands import pr_assets, upload_image-_KEY_RE = r"\d{4}/\d{2}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"+_URL = "https://raw.githubusercontent.com/PostHog/pr-assets/abc123/2026/07/f7c1.png"@pytest.fixture@@ -29,77 +30,53 @@ def png(tmp_path: Path) -> Path:return path-def _resp(status: int, sha: str | None = None) -> SimpleNamespace:- return SimpleNamespace(- status_code=status,- ok=status < 400,- json=lambda: {"commit": {"sha": sha}} if sha is not None else {},- )+@contextmanager+def _publishes(*urls: str) -> Iterator[Mock]:+ """Stand in for storage so these tests turn on the command, not the GitHub wire format."""+ with patch.object(pr_assets, "publish", return_value=list(urls)) as publish:+ yield publish-def _session(*responses: SimpleNamespace) -> Mock:- session = Mock()- session.put.side_effect = responses- return session---def test_command_prints_only_sha_pinned_markdown_to_stdout(png: Path, monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setenv("GH_TOKEN", "tok") # token via the real env path- with patch.object(upload_image.requests, "Session", return_value=_session(_resp(201, "abc123"))):+def test_command_prints_only_markdown_to_stdout(png: Path) -> None:+ with _publishes(_URL):result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, ["--yes", str(png)])assert result.exit_code == 0- line = result.stdout.strip()- assert re.fullmatch(- rf"!\[diagram\]\(https://raw\.githubusercontent\.com/PostHog/pr-assets/abc123/{_KEY_RE}\.png\)", line- )+ assert result.stdout.strip() == f""# the public-repo warning must reach stderr, never stdout (stdout is piped into PRs verbatim)assert "PUBLIC" in result.stderrassert "PUBLIC" not in result.stdout@pytest.mark.parametrize(- ("alt", "expected_prefix"),+ ("alt", "expected_label"),[- ("before / after", ",- ("", "!["),- ("chart]v2", "![chart\\]v2]("),- ("chart\\]v2", "![chart\\\\\\]v2]("),+ ("before / after", "before / after"),+ ("", ""),+ ("chart]v2", "chart\\]v2"),+ ("chart\\]v2", "chart\\\\\\]v2"),],ids=["override", "empty_honored", "bracket_escaped", "backslash_escaped"],)-def test_command_caption_rendering(png: Path, monkeypatch: pytest.MonkeyPatch, alt: str, expected_prefix: str) -> None:+def test_command_caption_rendering(png: Path, alt: str, expected_label: str) -> None:# --alt is used verbatim (empty stays empty, not replaced by the stem) and its markdown# metacharacters are escaped so a `]` can't truncate the embed.- monkeypatch.setenv("GH_TOKEN", "tok")- with patch.object(upload_image.requests, "Session", return_value=_session(_resp(201, "abc123"))):+ with _publishes(_URL):result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, ["--yes", "--alt", alt, str(png)])- assert result.stdout.strip().startswith(expected_prefix)+ assert result.stdout.strip() == f""-def test_requires_yes_before_uploading(png: Path, monkeypatch: pytest.MonkeyPatch) -> None:+def test_requires_yes_before_uploading(png: Path) -> None:# The gate: a first run without --yes must warn and abort without uploading, so the# caller has to read the warning and re-run to confirm the public upload.- monkeypatch.setenv("GH_TOKEN", "tok")- session = _session(_resp(201, "x"))- with patch.object(upload_image.requests, "Session", return_value=session):+ with _publishes(_URL) as publish:result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, [str(png)])assert result.exit_code != 0assert "--yes" in result.stderrassert not result.stdout # no markdown emitted- session.put.assert_not_called()---def test_command_errors_without_a_token(png: Path, monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.delenv("GH_TOKEN", raising=False)- monkeypatch.delenv("GITHUB_TOKEN", raising=False)- monkeypatch.setattr(github_auth.shutil, "which", lambda _: None) # no env, no gh -> no token- result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, ["--yes", str(png)])-- assert result.exit_code != 0- assert "token" in result.stderr.lower()+ publish.assert_not_called()def test_rejects_alt_with_multiple_files(tmp_path: Path) -> None:@@ -108,10 +85,14 @@ def test_rejects_alt_with_multiple_files(tmp_path: Path) -> None:a, b = tmp_path / "a.png", tmp_path / "b.png"a.write_bytes(b"x")b.write_bytes(b"y")- result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, ["--yes", "--alt", "shared", str(a), str(b)])+ with _publishes(_URL, _URL) as publish:+ result = CliRunner(mix_stderr=False).invoke(+ upload_image.upload_image, ["--yes", "--alt", "shared", str(a), str(b)]+ )assert result.exit_code != 0assert "--alt" in result.stderr+ publish.assert_not_called()@pytest.mark.parametrize("name", ["notes.txt", "clip.mp4", "diagram.svg"], ids=["txt", "mp4", "svg"])@@ -120,19 +101,17 @@ def test_image_allowlist_rejects_non_image_extensions(tmp_path: Path, name: str)# text/plain, so GitHub won't inline it).path = tmp_path / namepath.write_bytes(b"data")- with pytest.raises(pr_assets.click.ClickException, match="unsupported"):- pr_assets.validate(path, upload_image._ALLOWED_EXTS, upload_image._MAX_MB)+ with pytest.raises(click.ClickException, match="unsupported"):+ pr_assets.validate(path, upload_image._KIND.allowed_exts, upload_image._KIND.max_mb)-def test_symlink_is_rejected_on_stderr_without_any_upload(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+def test_symlink_is_rejected_without_any_upload(tmp_path: Path) -> None:target = tmp_path / "secret.env"target.write_bytes(b"SECRET=1")link = tmp_path / "screenshot.png"link.symlink_to(target)- monkeypatch.setenv("GH_TOKEN", "tok")- session = _session(_resp(201, "x"))- with patch.object(upload_image.requests, "Session", return_value=session):+ with _publishes(_URL) as publish:result = CliRunner(mix_stderr=False).invoke(upload_image.upload_image, ["--yes", str(link)])assert result.exit_code != 0- session.put.assert_not_called()+ publish.assert_not_called()diff --git a/tools/hogli-commands/hogli_commands/tests/test_upload_video.py b/tools/hogli-commands/hogli_commands/tests/test_upload_video.pyindex d6b960cac27f..d86faee1575b 100644--- a/tools/hogli-commands/hogli_commands/tests/test_upload_video.py+++ b/tools/hogli-commands/hogli_commands/tests/test_upload_video.py@@ -1,25 +1,25 @@"""Tests for hogli pr:upload-video.-The shared upload plumbing (key shape, base64 body, 409 retry, validation gates) is-pinned in ``test_pr_assets``; these guard what is video-specific: the extension-allowlist, the link-style markdown on stdout (a plain [label](url), never an image-embed, since GitHub renders no player for raw-hosted video), the "add video" commit-message, and the --yes gate.+The storage contract is pinned in ``test_pr_assets``; these guard what is+video-specific: the extension allowlist, the link-style markdown on stdout (a plain+[label](url), never an image embed, since GitHub renders no player for raw-hosted+video), the "add video" commit message, and the --yes gate."""from __future__ import annotations-import re+from collections.abc import Iterator+from contextlib import contextmanagerfrom pathlib import Path-from types import SimpleNamespaceimport pytestfrom unittest.mock import Mock, patch+import clickfrom click.testing import CliRunnerfrom hogli_commands import pr_assets, upload_video-_URL_RE = r"https://raw\.githubusercontent\.com/PostHog/pr-assets/deadbeef/\d{4}/\d{2}/[0-9a-f-]+\.mp4"+_URL = "https://raw.githubusercontent.com/PostHog/pr-assets/deadbeef/2026/07/a91c.mp4"@pytest.fixture@@ -29,18 +29,10 @@ def mp4(tmp_path: Path) -> Path:return path-def _resp(status: int, sha: str | None = None) -> SimpleNamespace:- return SimpleNamespace(- status_code=status,- ok=status < 400,- json=lambda: {"commit": {"sha": sha}} if sha is not None else {},- )---def _session(*responses: SimpleNamespace) -> Mock:- session = Mock()- session.put.side_effect = responses- return session+@contextmanager+def _publishes(*urls: str) -> Iterator[Mock]:+ with patch.object(pr_assets, "publish", return_value=list(urls)) as publish:+ yield publish@pytest.mark.parametrize("name", ["reel.gif", "still.png", "notes.txt"], ids=["gif", "png", "txt"])@@ -49,54 +41,44 @@ def test_video_allowlist_rejects_non_video_extensions(tmp_path: Path, name: str)# pr:upload-image.path = tmp_path / namepath.write_bytes(b"data")- with pytest.raises(pr_assets.click.ClickException) as excinfo:- pr_assets.validate(path, upload_video._ALLOWED_EXTS, upload_video._MAX_MB)+ with pytest.raises(click.ClickException) as excinfo:+ pr_assets.validate(path, upload_video._KIND.allowed_exts, upload_video._KIND.max_mb)assert "mp4" in str(excinfo.value) and "webm" in str(excinfo.value)-def test_without_yes_uploads_nothing_and_exits_nonzero(mp4: Path, monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setenv("GH_TOKEN", "tok")- session = _session(_resp(201, "x"))- with patch.object(upload_video.requests, "Session", return_value=session):+def test_without_yes_uploads_nothing_and_exits_nonzero(mp4: Path) -> None:+ with _publishes(_URL) as publish:result = CliRunner(mix_stderr=False).invoke(upload_video.upload_video, [str(mp4)])assert result.exit_code == 1assert not result.stdout- session.put.assert_not_called()+ publish.assert_not_called()-def test_stdout_is_link_markdown_not_image_embed(mp4: Path, monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setenv("GH_TOKEN", "tok")- with patch.object(upload_video.requests, "Session", return_value=_session(_resp(201, "deadbeef"))):+def test_stdout_is_link_markdown_not_image_embed(mp4: Path) -> None:+ with _publishes(_URL):result = CliRunner(mix_stderr=False).invoke(upload_video.upload_video, ["--yes", str(mp4)])assert result.exit_code == 0- lines = result.stdout.strip().splitlines()- assert len(lines) == 1- assert re.fullmatch(r"\[frontend-qa\]\(" + _URL_RE + r"\)", lines[0])- assert not lines[0].startswith("!") # a video embed renders as a broken image on GitHub+ # a video embed renders as a broken image on GitHub, so the leading "!" must stay off+ assert result.stdout.strip() == f"[frontend-qa]({_URL})"-def test_upload_uses_video_commit_message(mp4: Path, monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setenv("GH_TOKEN", "tok")- session = _session(_resp(201, "deadbeef"))- with patch.object(upload_video.requests, "Session", return_value=session):+def test_upload_uses_video_commit_message(mp4: Path) -> None:+ with _publishes(_URL) as publish:result = CliRunner(mix_stderr=False).invoke(upload_video.upload_video, ["--yes", str(mp4)])assert result.exit_code == 0- assert session.put.call_args.kwargs["json"]["message"] == "add video"+ assert publish.call_args.kwargs["message"] == "add video"-def test_label_rejected_for_multiple_files(mp4: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- # Isolate the network so a guard regression fails loudly here instead of PUTting to- # the public repo from a token-bearing machine.+def test_label_rejected_for_multiple_files(mp4: Path, tmp_path: Path) -> None:other = tmp_path / "second.webm"other.write_bytes(b"webm fake")- monkeypatch.setenv("GH_TOKEN", "tok")- session = _session(_resp(201, "x"))- with patch.object(upload_video.requests, "Session", return_value=session):+ with _publishes(_URL, _URL) as publish:result = CliRunner(mix_stderr=False).invoke(upload_video.upload_video, ["--yes", "--label", "demo", str(mp4), str(other)])+assert result.exit_code != 0- session.put.assert_not_called()+ publish.assert_not_called()diff --git a/tools/hogli-commands/hogli_commands/upload_image.py b/tools/hogli-commands/hogli_commands/upload_image.pyindex ab670a0e7752..582ad2def121 100644--- a/tools/hogli-commands/hogli_commands/upload_image.py+++ b/tools/hogli-commands/hogli_commands/upload_image.py@@ -1,9 +1,8 @@"""hogli pr:upload-image: upload screenshots to the public PostHog/pr-assets repo.-Wraps the GitHub contents API upload documented in the pr-assets README so engineers-and agents can turn a local screenshot into an embeddable, SHA-pinned markdown image-line for a PR description with one command. Running through hogli means the usage is-tracked by hogli's built-in command telemetry.+Turns a local screenshot into an embeddable, commit-pinned markdown image line for a PR+description in one command. Running through hogli means the usage is tracked by hogli's+built-in command telemetry.Auth reuses a GitHub token from GH_TOKEN/GITHUB_TOKEN or the gh CLI (`gh auth token`),so it works with or without gh installed as long as a token with write access to a@@ -18,15 +17,18 @@ from pathlib import Pathfrom typing import Finalimport click-import requests-from hogli_commands import pr_assets-from hogli_commands.github_auth import github_token+from hogli_commands.pr_upload import AssetKind, run-# svg is excluded: raw.githubusercontent.com serves it as text/plain, so GitHub won't inline it-_ALLOWED_EXTS: Final = frozenset({"png", "jpg", "jpeg", "gif", "webp"})-_MAX_MB: Final = 10 # GitHub caps image/gif attachments at 10 MB; larger is a video or wrong file-_COMMIT_MESSAGE: Final = "add screenshot"+_KIND: Final = AssetKind(+ noun="image",+ caption_flag="--alt",+ # svg is excluded: raw.githubusercontent.com serves it as text/plain, so GitHub won't inline it+ allowed_exts=frozenset({"png", "jpg", "jpeg", "gif", "webp"}),+ max_mb=10, # GitHub caps image/gif attachments at 10 MB; larger is a video or wrong file+ commit_message="add screenshot",+ markdown="",+)@click.command(name="pr:upload-image")@@ -51,36 +53,4 @@ def upload_image(files: tuple[Path, ...], alt: str | None, yes: bool) -> None:permanent: SHA-pinned URLs keep serving even after the file is deleted. Never uploadcustomer data, secrets, or internal-only information."""- click.secho(pr_assets.PUBLIC_WARNING, fg="yellow", bold=True, err=True)-- if alt is not None and len(files) > 1:- raise click.ClickException("--alt captions a single image; drop it to caption each file with its stem")-- validated = [(path, pr_assets.validate(path, _ALLOWED_EXTS, _MAX_MB)) for path in files]-- # Deliberate speed bump: make the caller read the warning above and re-run to confirm.- if not yes:- click.secho(- "\nNothing uploaded. If the image is safe to publish (no customer data, secrets, or internal "- "info), re-run the same command with --yes to confirm.",- fg="yellow",- err=True,- )- raise SystemExit(1)-- token = github_token()- if token is None:- raise click.ClickException(- "no GitHub token found. Set GH_TOKEN or GITHUB_TOKEN, or install gh "- "(https://cli.github.com/) and run `gh auth login`."- )- session = requests.Session()-- for path, ext in validated:- key = pr_assets.make_key(ext)- click.secho(f"Uploading {path.name} → {pr_assets.REPO}/{key} …", fg="cyan", err=True)- sha = pr_assets.upload(path, key, token, session, message=_COMMIT_MESSAGE)- caption = alt if alt is not None else path.stem- markdown = f""- click.echo(markdown) # stdout carries only the markdown, so callers can pipe it- click.secho(f"✓ uploaded {path.name}", fg="green", err=True)+ run(files, alt, yes, _KIND)diff --git a/tools/hogli-commands/hogli_commands/upload_video.py b/tools/hogli-commands/hogli_commands/upload_video.pyindex 90eeff90a53f..42a1114af426 100644--- a/tools/hogli-commands/hogli_commands/upload_video.py+++ b/tools/hogli-commands/hogli_commands/upload_video.py@@ -1,7 +1,7 @@"""hogli pr:upload-video: upload short demo videos to the public PostHog/pr-assets repo.-Same storage, auth, and confirmation gate as pr:upload-image (the shared pr_assets-client), but for video files. GitHub renders no inline player for raw-hosted video, so+Same storage, auth, and confirmation gate as pr:upload-image (the shared pr_upload+body), but for video files. GitHub renders no inline player for raw-hosted video, sothe printed markdown is a plain [label](url) link that opens or downloads the filerather than an embed. For an inline player, drag the video into the PR comment editorby hand instead.@@ -13,17 +13,20 @@ from pathlib import Pathfrom typing import Finalimport click-import requests-from hogli_commands import pr_assets-from hogli_commands.github_auth import github_token+from hogli_commands.pr_upload import AssetKind, run-_ALLOWED_EXTS: Final = frozenset({"mp4", "webm"})-# GitHub's own inline-upload cap for videos on free plans, and roomy for the intended-# use: a 10-30 s screen recording of the app at 1280px wide (H.264, CRF 26) comes out-# around 250-650 KB, so 10 MB fits several minutes of UI screencast.-_MAX_MB: Final = 10-_COMMIT_MESSAGE: Final = "add video"+_KIND: Final = AssetKind(+ noun="video",+ caption_flag="--label",+ allowed_exts=frozenset({"mp4", "webm"}),+ # GitHub's own inline-upload cap for videos on free plans, and roomy for the intended+ # use: a 10-30 s screen recording of the app at 1280px wide (H.264, CRF 26) comes out+ # around 250-650 KB, so 10 MB fits several minutes of UI screencast.+ max_mb=10,+ commit_message="add video",+ markdown="[{label}]({url})",+)@click.command(name="pr:upload-video")@@ -48,37 +51,4 @@ def upload_video(files: tuple[Path, ...], label: str | None, yes: bool) -> None:SHA-pinned URLs keep serving even after the file is deleted. Never upload customerdata, secrets, or internal-only information."""- click.secho(pr_assets.PUBLIC_WARNING, fg="yellow", bold=True, err=True)-- if label is not None and len(files) > 1:- raise click.ClickException("--label captions a single video; drop it to label each file with its stem")-- validated = [(path, pr_assets.validate(path, _ALLOWED_EXTS, _MAX_MB)) for path in files]-- if not yes:- click.secho(- "\nNothing uploaded. If the video is safe to publish (no customer data, secrets, or internal "- "info), re-run the same command with --yes to confirm.",- fg="yellow",- err=True,- )- raise SystemExit(1)-- token = github_token()- if token is None:- raise click.ClickException(- "no GitHub token found. Set GH_TOKEN or GITHUB_TOKEN, or install gh "- "(https://cli.github.com/) and run `gh auth login`."- )- session = requests.Session()-- for path, ext in validated:- key = pr_assets.make_key(ext)- click.secho(f"Uploading {path.name} → {pr_assets.REPO}/{key} …", fg="cyan", err=True)- sha = pr_assets.upload(path, key, token, session, message=_COMMIT_MESSAGE)- text = label if label is not None else path.stem- markdown = (- f"[{pr_assets.escape_markdown_label(text)}](https://raw.githubusercontent.com/{pr_assets.REPO}/{sha}/{key})"- )- click.echo(markdown) # stdout carries only the markdown, so callers can pipe it- click.secho(f"✓ uploaded {path.name}", fg="green", err=True)+ run(files, label, yes, _KIND)